实体框架 - 通过集合导航和包含属性

时间:2010-09-23 16:59:15

标签: linq-to-entities c#-4.0 entity-framework-4 code-first

我刚刚有一个巨大的*blonde moment**,但它强调了我对Entity Framework的烦恼。我已经禁用了延迟加载,因此我强迫自己实际考虑我需要哪些数据以尽可能快地保持应用程序。

因此,为了在查询中返回数据,我需要使用Include方法:

var query = from item in context.Customers
                .Include(x=> x.Orders)
            select item

这很好,直到我想在层次结构中选择更深入的项目。即:

Customer 1-* Orders *-1 Factory 1-1 Factory Type

据我所知,返回所有这些数据 急切 的唯一方法是执行以下操作:

var query = from item in context.Customers
                .Include("Orders.Factory.FactoryType")
            select item

根据上述情况,我无法按照我的第一个例子使用System.Data.Entity Lambdas。有没有人知道我在这里是否遗漏了一些明显的东西,还是我坚持使用字符串声明通过集合导航属性?

如果我没有任何收藏品,我可以写:

.Include(x=> x.Order.OrderType.Factory.FactoryType) // No bother

但是由于Orders集合,就我所知(FirstOrDefaultSingleOrDefault等不起作用而言),无法单步执行子属性。


**这只是一个转折,我碰巧非常喜欢金发女郎*

1 个答案:

答案 0 :(得分:14)

要包含EntityCollections,请使用 选择 方法:

var query = from item in context.Customers
           .Include(c => c.Orders.Select(o => o.Factory.FactoryType))
           select item

请注意,这不是标准ObjectQuery<T>.Include Method的重载,仅仅是 ObjectQuery<T> 类的扩展方法 EF CTP4 < /强>