linq with Include和criteria

时间:2011-06-24 00:00:56

标签: linq entity-framework

我如何将其翻译成LINQ?

假设我有一个父表(Say,customers)和子(地址) 我想退回所有在加利福尼亚州有地址的家长,以及加利福尼亚州的地址。 (但我想在LINQ中进行并获取Entity对象的对象图)

这是老式的方式:


SELECT c.blah, a.blah
FROM Customer c
INNER JOIN Address a on c.CustomerId = a.CustomerId
where a.State = 'CA'

我对LINQ的问题是我需要一个具体实体类型的对象图(它不能延迟加载。

这是我到目前为止所尝试的内容:

编辑:按要求添加了上下文实例化


// this one doesn't filter the addresses -- I get the right customers, but I get all of their addresses, and not just the CA address object.

var ctx = new CustomersContext() // dbContext -- using EF 4.1 

from c in ctx.Customer.Include(c => c.Addresses)
where c.Addresses.Any(a => a.State == "CA")
select c

// this one seems to work, but the Addresses collection on Customers is always null
var ctx = new CustomersContext() // dbContext -- using EF 4.1 
from c in ctx.Customer.Include(c => c.Addresses)
from a in c.Addresses
where a.State == "CA"
select c;

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

根据上面的代码,您似乎已在Customer变量中拥有一个重新合并的Customer对象集合。

当您填写上面的Include集合时,您需要拨打Customer功能。这样,框架将在从数据上下文中检索时重新包含所包含的对象。

但实际的查询代码看起来不错。

相关问题