我刚开始使用Entity Framework Core在VS2017 ASP.NET Core中使用WebAPI模板,我正在尝试找出返回特定Get请求的对象属性子集的最佳方法。
我最初使用内置的脚手架来生成控制器,它最初生成的Get
请求方法如下所示:
[HttpGet]
public IEnumerable<Person> GetPeople()
{
return _context.People;
}
我的问题是,当有人打电话给Person
时,GetPeople()
有一个我不想要的儿童班。
因为我不想返回一个匿名对象,所以我在控制器中添加了一个名为PersonInfo
的精简版,它只包含我想要返回的属性,如下所示:
public class PersonInfo
{
public int id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string AD { get; set; }
}
然后我将GetPeople()
方法更新为:
[HttpGet]
public IEnumerable<PersonInfo> GetPeople()
{
List<PersonInfo> pi = new List<PersonInfo>();
foreach(var person in _context.People
.Select(p => new { p.id, p.FirstName, p.LastName, p.AD})
.ToList())
{
PersonInfo newPerson = new PersonInfo();
newPerson.id = person.id;
newPerson.FirstName = person.FirstName;
newPerson.LastName = person.LastName;
newPerson.AD = person.AD;
pi.Add(newPerson);
}
return pi;
}
这很好用,只是感觉非常低效。必须有更好的方法,对吗?
这确实非常低效。该方法应如下所示:
[HttpGet]
public async Task<IEnumerable<PersonInfo>> GetPeople()
{
return await _context.People
// select the data you want directly
.Select(p => new PersonInfo
{
id = p.id,
FirstName = p.FirstName,
LastName = p.LastName,
AD = p.AD
})
// always use the asynchronous version of EF Core extension methods
.ToListAsync();
}
顺便说一下,你应该习惯在ASP.NET Core中使用IActionResult
接口。这使您可以轻松自定义状态代码以及返回数据的方式。使用类似的东西更为可取:
[HttpGet]
public async Task<IActionResult> GetPeople()
{
var data = await _context.People
// select the data you want directly
.Select(p => new PersonInfo
{
id = p.id,
FirstName = p.FirstName,
LastName = p.LastName,
AD = p.AD
})
// always use the asynchronous version of EF Core extension methods
.ToListAsync();
return Json(data);
}