2017-10-09 34 views
0

场景:投诉对象可以有很多投票。在所有投诉的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)在Ap​​pDbContext.cs文件,以便我可以实际加载投票以确定投票计数。

我不想将投票计数存储为实际的数据库列。

任何意见将不胜感激!

我正在使用.NET Core 2.0 Web API与实体框架核心。

在此先感谢。

+1

嗨,你不应该让你的数据库对象通过webapi.You应创建DTO(数据传输对象),一旦你从数据库中获得的结果,你应该映射结果DTO并返回DTO作为响应。 如果您确实需要公开您的数据库对象,那么您可以尝试在列表 Vots上添加[JsonIgnore]属性。我鼓励你去DTO。 –

回答

0

您可以在类中使用选择启用会员系列化:

//.. 
using Newtonsoft.Json; 
//.. 

[JsonObject(MemberSerialization.OptIn)] 
public class Complaint 
{ 
    [JsonProperty("id")] 
    public int Id { get; set; } 
    [JsonProperty("summary")] 
    public string Summary { get; set; } 
    public List<Vote> Votes { get; set; } 
    [JsonProperty("upVoteCount")] 
    public int UpVoteCount=> Votes.Count(v => v.IsUpvote); 
    public ApplicationUser Creator { get; set; } 
} 
0

也许是这样的:

public List<Complaint> ComplaintsWithData() 
{ 
    return this.DbContext.Complaints 
     .Include(complaint => complaint.Votes) 
     .Select(p => new Complaint 
     { 
      Id = p.Id, 
      IsUpVote = p.IsUpVote, 
      UpVoteCount = p.Votes.Count 
     }).ToList(); 
} 
0

有几种选择。以下是其中两个:

您可能会考虑添加视图模型 - 具有您想要返回到UI的一组确切属性的类。您只需要将您的实体记录映射到他们

或者只是标记你想隐藏被序列化到您的JSONXML端点响应NonSerialized属性属性。

public class Complaint 
{ 
    public int Id { get; set; } 
    public string Summary { get; set; } 
    [NonSerialized] 
    public List<Vote> Votes { get; set; } 
    public int UpVoteCount=> Votes.Count(v => v.IsUpvote); 
    public ApplicationUser Creator { get; set; } 
}