gpt4 book ai didi

c# - 如何正确返回对象属性的子集

转载 作者:行者123 更新时间:2023-11-30 21:32:34 25 4
gpt4 key购买 nike

我刚开始使用 Entity Framework Core 在 VS2017 ASP.NET Core 中使用 WebAPI 模板,我正在尝试找出为特定 Get 请求返回对象属性子集的最佳方法。

我最初使用内置的脚手架来生成一个 Controller ,它最初生成的Get请求方法是这样的:

[HttpGet]
public IEnumerable<Person> GetPeople()
{
return _context.People;
}

我的问题是 Person 有一个子类,当有人调用 GetPeople() 时我不想包含它。

因为我不想返回匿名对象,所以我在名为 PersonInfo 的 Controller 中添加了一个精简类,它只有我想要返回的属性,如下所示:

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 接口(interface)。这使您可以轻松自定义状态代码以及返回数据的方式。使用类似的东西更可取:

[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);
}

关于c# - 如何正确返回对象属性的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52205841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com