EF 4.通过LINQ to Entities选择两级层次结构

时间:2013-01-28 15:40:40

标签: entity-framework linq-to-entities entity

有Cars实体集,每辆Car都有一套AdvancedCodes。 最近我使用方法表示法从我的EF存储中选择层次结构。它看起来像这样:

repository.Cars.Where(a => a.AgentId == userAgent.AgentId)
      .Include(a => a.AdvancedCodes)
      .Where(a => a.CarId != null).ToList()

我在每辆车内收到了带有AdvancedCodes集合的汽车收藏。太棒了。 现在我需要切换到LINQ-to-Entities表示法来执行多个LEFT连接和更复杂的SELECT:

from cr in context.Cars
from ac in context.AdvancedCodes.Where(a => a.CarId == cr.CarId).DefaultIfEmpty()
from c in context.Contacts.Where(a => a.AdvancedCodeId == ac.AdvancedCodeId).DefaultIfEmpty()
from ag in context.Agents.Where(a => a.AgentId == ac.AdvancedCodeId).DefaultIfEmpty()
where ac.AgentId == agentId && ac.CarId != null && cr.IsApproved == true
select new CarCodeModel
{
     CarBrand = cr.CarBrand.BrandName,
     RegNumber = cr.RegNumber, 
     ContactDate = c.DateCreated,
     ContactCode = ac.Code,
     CodeCreationDate = ac.DateCreated,
     IsUsed = c.CoId != null,
     RecepientName = ag.AgentName
};

没关系,但这次我得到了一套平面的2D数据集,我需要以某种方式迭代并拆分两个相关的集合。有没有办法编写更复杂的查询来获得与.Include方法之后相同的两级集合?

0 个答案:

没有答案