Linq/EF、预加载和 GROUP BY 问题
我在 GROUP BY 和急切加载方面遇到问题。我尝试解释我在做什么。 我正在查询事件的数据上下文 ctx
事件类具有以下属性
string Description
DateTime Date
bool IsDeleted
Guid SubjectId
string Title
DateTime Created
Guid ForProjectId
Person TriggeredBy
List<Guid> Targets
有多个具有相同主题 ID 的事件,我希望最终拥有具有唯一主题 ID 的事件,并且这些事件是组中最新的。我最终得到以下查询。
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();
查询编译良好并返回正确的结果集。但包含的属性始终为空。
当我删除查询以查看急切加载是否正常工作时...
var events = (from e in ctx.Events.OfType<DataNotificationEvent>()
.Include("TriggeredBy")
.Include("Targets")
select e).ToList();
这将返回具有所有包含属性的事件。
这是 Linq / EF 的已知问题/错误吗?或者有什么方法可以消除此错误。
问候 文
森特·奥滕斯
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
The event class has the following properties
string Description
DateTime Date
bool IsDeleted
Guid SubjectId
string Title
DateTime Created
Guid ForProjectId
Person TriggeredBy
List<Guid> Targets
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();
The query compile fine and returns the right resulting set. But the included properties are always null.
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.
Is this a known issue / bug with Linq / EF or is there any way i can get rid of this error.
Regards
Vincent Ottens
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在投影到匿名类型,因此
Include()
不会像那样工作。因为您对group
所做的操作以及投影到匿名类型的目的是更改查询的形状。这会消除急切的加载。阅读这篇文章< /a> 可能有帮助。You're projecting onto an anonymous type, so
Include()
isn't going to work like that. Because what you've done with thegroup
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.感谢您的快速回答。你为我指明了正确的方向。这是我想出的解决方案:
Thnx for the quick answer. You pointed me in the right direction. Here is the solution i came up with: