C# 在实体框架中,如何在同一查询中使用Include和Anonymous类型?
我得到了这个问题 但是当我访问queryResult[0].post.Category或queryResult[0].post.Tags时,它总是空的,因为我没有使用Include 包括“不使用投影”,正如microsoft在此处最后一项所说: 如何在同一查询中获得计数,并包括与标记和类别的关系C# 在实体框架中,如何在同一查询中使用Include和Anonymous类型?,c#,linq,entity-framework,entity-framework-4,linq-to-entities,C#,Linq,Entity Framework,Entity Framework 4,Linq To Entities,我得到了这个问题 但是当我访问queryResult[0].post.Category或queryResult[0].post.Tags时,它总是空的,因为我没有使用Include 包括“不使用投影”,正如microsoft在此处最后一项所说: 如何在同一查询中获得计数,并包括与标记和类别的关系 为什么EF关系修复在这里不起作用?这可以通过两个查询完成: var posts = from post in context.Posts.Include(p => p.Author).Incl
为什么EF关系修复在这里不起作用?这可以通过两个查询完成:
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]);
}
迭戈·维加:它应该可以正常工作。可能您的模型类有问题。你能在这个问题上添加EF代码吗?我做了一些研究,这是预期的行为。关系修复不适用于多对多相似的问题,并给出有效的答案:
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]);
}