【发布时间】:2016-11-21 17:45:23
【问题描述】:
我有 2 个描述 Post 和 Comments 的实体。
public class Post
{
public int Id { get; set; }
public ICollection<Comment> Comments { get; set; }
//other properties
//Unmapped property
public int NumberOfComments { get; set; }
}
public class Comment
{
public int Id { get; set; }
public Post Post { get; set; }
public int PostId { get; set; }
// other properties
}
现在我希望 NumberOfComments 属性填充帖子的实际 cmets 计数。
尝试将查询结果投影到帖子集合中 模特没有锻炼。
尝试加入表格,然后按帖子 ID 分组仍然没有 似乎有效。
我不能简单地将 return p.Comments.Count; 作为属性定义,因为我在查询期间不包括 cmets。我只想要 cmets 的计数,而不是内存中的整个集合。
【问题讨论】:
-
public int NumberOfComments { get { return Comments.Count(); } }? -
我不包括 cmets。我只想获取 cmets 的数量。
-
我认为您必须在查询中明确请求它
select new Post { Id = p.Id, NumberOfComments = p.Comments.Count()}? -
juharr 谢谢。但它会抛出“无法在 linq 到实体查询中构造实体”
-
@Aneef 然后就做类似
... select new { Id= p.Id, NumberOfComments = p.Comments.Count() }).AsEnumerable().Select(p => new Post { Id = p.Id, NumberOfComments = p.NumberOfComments})的事情。或者考虑为您要使用的特定数据创建一个单独的 DTO,并将您的其他层与您的实体分开。
标签: c# sql entity-framework entity-framework-6