在How To Count Associated Entities using Where In Entity Framework我得到这个查询
但是当我访问 queryResult[0].post.Category 或 queryResult[0].post.Tags 时它总是空的,因为我没有使用 Include。
包括不使用 Projection,正如微软在此处最后一项所说:http://msdn.microsoft.com/en-us/library/bb896317.aspx
var queryResult = (from post in posts
join comment in comments.Where(x=> x.IsPublic) on post.Id equals comment.Post.Id into g
select new
{
post,
post.Author,
post.Tags,
post.Categories,
Count = g.Count()
})
如何在同一查询中获取计数,并包含与标签和类别的关系?
为什么 EF 关系修复在这里不起作用?
最佳答案
这可以通过 2 个查询来完成:
var posts =
from post in context.Posts.Include(p => p.Author).Include(p => p.Tags).Include(p => p.Categories)
where post.Comments.Any(c => c.IsPublic)
select post;
var counts =
from post in context.Posts
where post.Comments.Any(c => c.IsPublic)
select new { PostId = post.Id, Count = post.Comments.Count() };
var countDictionary = counts.ToDictionary(e => e.PostId, e => e.Count);
foreach (var item in posts)
{
System.Console.WriteLine("PostId {0}, TagCount {1}, PublicCommentCount {2}", item.Id, item.Tags.Count, countDictionary[item.Id]);
}
迭戈·维加:http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/c0bae1c1-08b2-44cb-ac29-68a6518d87bd
关于c# - 如何在 Entity Framework 的同一查询中使用包含和匿名类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5026266/