Linq/EF,急切加载和GROUP BY问题 [英] Linq/EF, Eager loading and GROUP BY issues

查看:82
本文介绍了Linq/EF,急切加载和GROUP BY问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在GROUP BY和渴望加载方面遇到问题.我试图解释我在做什么. 我正在查询数据上下文ctx中的事件

I'm having issues with GROUP BY and eager loading. I try to explain what im doing. I'm querying a datacontext ctx for events

事件类具有以下属性

string Description
DateTime Date
bool IsDeleted
Guid SubjectId 
string Title 
DateTime Created
Guid ForProjectId 

Person TriggeredBy
List<Guid> Targets 

有多个具有相同SubjectId的事件,我希望最终拥有具有唯一SubjectId的事件,并且这是该组中的最新事件.我最终得到以下查询.

There are muttiple events with the same SubjectId and i would like to end up having events with unique SubjectIds and that are the newest in the group. I end up with the following query.

var events = from x in
             (from e in ctx.Events
              .Include("TriggeredBy")
              .Include("Targets")
              group e by e.SubjectId
              into g
              select new 
                     { 
                       GroupId = g.Key, 
                       EventsWithSameSubjectId = g, 
                     }
              )
              select x.EventsWithSameSubjectId
              .OrderByDescending(y => y.Created).FirstOrDefault();

查询可以正常编译并返回正确的结果集.但是包含的属性始终为null.

The query compile fine and returns the right resulting set. But the included properties are always null.

当我剥离查询以查看eagor加载是否正常工作时....

When i strip the query to see if eagor loading is working properly....

var events =  (from e in ctx.Events.OfType<DataNotificationEvent>()
              .Include("TriggeredBy")
              .Include("Targets")
              select e).ToList();

这将返回具有所有包含的属性的事件.

This return the events with all the included properties.

这是Linq/EF的已知问题/错误,还是有什么办法可以消除此错误?

Is this a known issue / bug with Linq / EF or is there any way i can get rid of this error.

致谢

Vincent Ottens

Vincent Ottens

推荐答案

您正在投影到匿名类型,因此Include()不会那样工作.因为您对group所做的并投影为匿名类型的操作是要更改查询的形状.这就扔掉了急切的负担.阅读本文可能有帮助.

You're projecting onto an anonymous type, so Include() isn't going to work like that. Because what you've done with the group and projecting into the anonymous type is to change the shape of the query. That tosses out the eager loading. Reading this article might help.

这篇关于Linq/EF,急切加载和GROUP BY问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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