【问题标题】:How to use Include and Anonymous Type in same query in Entity Framework?如何在实体框架的同一查询中使用包含和匿名类型?
【发布时间】:2011-02-17 07:41:47
【问题描述】:

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 关系修复在这里不起作用?

【问题讨论】:

  • 它应该可以正常工作。也许您的模型类有问题。你可以在这个问题中添加 EF Code First 代码吗?
  • 我做了一些研究,这是预期的行为。关系修复不适用于多对多
  • 有一个有效答案的类似问题:stackoverflow.com/questions/7167547/…

标签: c# linq entity-framework entity-framework-4 linq-to-entities


【解决方案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]);
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多