在Entity Framework中如何使用Include和Anonymous类型进行相同的查询? [英] How to use Include and Anonymous Type in same query in Entity Framework?

查看:108
本文介绍了在Entity Framework中如何使用Include和Anonymous类型进行相同的查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计数关联实体使用实体框架我得到这个查询

但是当我访问queryResult [0] .post.Category或queryResult [0] .post.Tags它总是空的,因为我没有使用Include。

But when I access queryResult[0].post.Category or queryResult[0].post.Tags it´s always empty, because I am not using Include.

包括不使用Projection,就像微软在最后一个项目中所说的那样: http://msdn.microsoft.com/en-us/library/bb896317.aspx

Include dont work with Projection, as microsoft say at last item here: 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()
                               })

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

How I can get the Count in the same query, and Include relationship to Tags and Categories?

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

Why EF relationship fix-up dont work here?

推荐答案

这可以用2个查询完成:

This can be done with 2 queries:

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]);
}

由Diego Vega: http://social.msdn.microsoft.com/Forums/en-US/adonetefx / thread / c0bae1c1-08b2-44cb-ac29-68a6518d87bd

By Diego Vega: http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/c0bae1c1-08b2-44cb-ac29-68a6518d87bd

这篇关于在Entity Framework中如何使用Include和Anonymous类型进行相同的查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆