Linq把Include放入select new

时间:2013-09-13 16:51:42

标签: c# linq entity-framework

我有这个linq查询,我想得到一个字典,值是实体的集合,我想在这个列表中使用include。

var keys = (from e in ctx.Events
            where (e.DeletedFlag == null || e.DeletedFlag == false) &&
            e.ModuleID == moduleId &&
            e.ParentID == null && 
            e.EventType == Core.Enum.EventType.Menu
            select new { 
                         Key = e,
                         Values = (from v in ctx.Events
                                   where (v.DeletedFlag == null || v.DeletedFlag == false) &&
                                   v.ModuleID == moduleId &&
                                   v.ParentID == e.PublicationID
                                   select v).Include(v => v.Document).Include(v => v.EventTAF).Include(v => v.Appointment)
                           }).ToList();

当我执行此查询时,我收到一条错误消息,指出linq无法识别Include方法。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您可以创建两个外部查询,然后将它们连接在一起,而不是使用内部查询:

var events = from e in ctx.Events
             where (e.DeletedFlag == null || e.DeletedFlag == false) &&
                 e.ModuleID == moduleId &&
                 e.ParentID == null && 
                 e.EventType == Core.Enum.EventType.Menu
                 select e;

var values = from v in ctx.Events
             where (v.DeletedFlag == null || v.DeletedFlag == false) &&
                 v.ModuleID == moduleId
             select v;
//TODO add Includes to values query

var query = from e in events
            join v in values
            on e.PublicationID equals v.ParentID into children
            select new
            {
                Key = e,
                Values = children,
            };

答案 1 :(得分:-1)

直接针对您的问题,如果名称空间中不存在Include Linq to Entities扩展方法,则需要确保存在对EF的引用(可能已经存在)并使用名称空间声明:

using System.Data;
using System.Data.Entity;
using System.Data.Linq;
using System.Data.Objects;