如何在Entity Framework中的同一查询中使用Include和Anonymous Type?

Fel*_*oto 5 c# linq linq-to-entities entity-framework entity-framework-4

如何使用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()
                               })
Run Code Online (Sandbox Code Playgroud)

我如何在同一个查询中获取Count,并包含与标签和类别的关系?

为什么EF关系修复不起作用?

Fel*_*oto 1

这可以通过 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]);
}
Run Code Online (Sandbox Code Playgroud)

作者:迭戈·维加:http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/c0bae1c1-08b2-44cb-ac29-68a6518d87bd