场景:投诉对象可以有很多投票。在所有投诉的GET请求中,我想要返回投票计数,而不是每个投票对象与API响应中的投诉。Web Api:使用EF包含成员字段数而不是成员对象数据返回JSON
这里的主要类型:
//Model: Complaint.cs
public class Complaint
{
public int Id { get; set; }
public string Summary { get; set; }
public List<Vote> Votes { get; set; }
public int UpVoteCount=> Votes.Count(v => v.IsUpvote);
public ApplicationUser Creator { get; set; }
}
//Model: Vote.cs
public class Vote
{
public int Id { get; set; }
public bool IsUpVote{ get; set; }
public Complaint Complaint { get; set; }
public ApplicationUser Creator { get; set; }
}
//DbContext: AppDbContext.cs
....
public IQueryable<Complaint> ComplaintsWithData =>
Complaint
.Include(complaint => complaint.Votes)
.AsNoTracking();
//ApiController: ComplaintsController.cs
[HttpGet]
public IEnumerable<Complaint> GetComplaints()
{
return _context.ComplaintsWithData.ToList();
}
在目前的JSON响应,我得到的计票结果,但我也得到每一个人的投票对象的详细信息,以及(我不要在此调用需要) 。
电流响应:
{
"id": 2,
"summary": "House was Stolen",
"votes": [
{
"id": 146,
"isUpvote": false,
"creator": null
},
{
"id": 147,
"isUpvote": false,
"creator": null
},
....
....
....
],
"upVoteCount": 211,
}
期望应答:
{
"id": 2,
"summary": "House was Stolen",
"upVoteCount": 211,
}
我需要有.INCLUDE(投诉=> complaint.Votes)在AppDbContext.cs文件,以便我可以实际加载投票以确定投票计数。
我不想将投票计数存储为实际的数据库列。
任何意见将不胜感激!
我正在使用.NET Core 2.0 Web API与实体框架核心。
在此先感谢。
嗨,你不应该让你的数据库对象通过webapi.You应创建DTO(数据传输对象),一旦你从数据库中获得的结果,你应该映射结果DTO并返回DTO作为响应。 如果您确实需要公开您的数据库对象,那么您可以尝试在列表 Vots上添加[JsonIgnore]属性。我鼓励你去DTO。 –