LINQ to Entities + Include +匿名类型问题 [英] LINQ To Entities + Include + Anonymous type issue

查看:65
本文介绍了LINQ to Entities + Include +匿名类型问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

类客户端

类项目

课票

类回复

客户端有一个子项目集合,项目有一个子

Clients have a sub collection of projects, projects have a sub collection of tickets and tickets have a sub collection of replies.

var data = ctx.Set<Ticket>().Include(p => p.Client).
Select(p => new { Ticket = p, LastReplyDate = p.Replies.Max(q => q.DateCreated)});

无效。当以这种方式选择数据时,项目和客户端都不会被加载。

Doesn't work. Neither project nor client are loaded when selecting data this way.

我知道如何使其工作。我的问题是为什么不这样工作?

I know how to make it work. My question is why doesn't it work like this?

推荐答案

正如Ladislav所说, Include 仅在您直接选择 Ticket 实体时有效。由于您投出了其他信息,因此 Include 将被忽略。

As Ladislav mentioned, Include only works if you select the Ticket entity directly. Since you're projecting other information out, the Include gets ignored.

这应该提供一个很好的解决方案:

This should provide a good work-around:

var data = ctx.Set<Ticket>()
    .Select(p => new 
         { 
             Ticket = p, 
             Clients = p.Client,
             LastReplyDate = p.Replies.Max(q => q.DateCreated)
         });

首先,每个Ticket的客户端将直接从客户端属性的匿名类型。此外,实体框架应该足够聪明,可以认识到您已经为每个 Ticket 删除了整个客户端集合调用 .Ticket.Client 应该也可以。

First of all, each Ticket's Clients will be accessible directly from the Clients property on the anonymous type. Furthermore, Entity Framework should be smart enough to recognize that you have pulled out the entire Client collection for each Ticket, so calling .Ticket.Client should work as well.

这篇关于LINQ to Entities + Include +匿名类型问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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