c# - 如何在 Entity Framework 的同一查询中使用包含和匿名类型?

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

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/

相关文章:

c# - 如何从数据表中设置dropdownlist的值?

c# - 如何序列化 IList<T> 等接口(interface)

c# - 如何过滤 xml 部分并将其保存为文件

asp.net-mvc - 使用不带主键的查找在dbSet中查找记录

c# - 如何选择列表的前 3 项 <>

c# - Entity Framework 代码优先多对多不使用 GUID 加载相关实体

c# - IEqualityComparer<T> 和 IEquatable<T> 有什么区别?

c# - 如何获取已安装的位图编码器/解码器列表(WPF 世界)?

sql-server - Async/Await 片段在以 MS-SQL-Server 为目标时发生死锁(如预期),但在以 Oracle 为目标时不会死锁(意外)

entity-framework - 如何在 Entity Framework 7 中运行自动映射到实体的动态 SQL 查询 (SqlQuery<T>)?