开发者

linq with Include and criteria

How would I translate this into LINQ?

Say I have A parent table (Say, customers), and child (addresses).

I want to return all of the Parents who have addresses in California, and just the california address. (but I want to do it in LINQ and get an object graph of Entity objects)

Here's the old fashioned way:


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

The problem I'm having with LINQ is that i need an object graph of concrete Entity types (and it can't be lazy loaded.

Here's what I've tried so far:

Edit: added context instantiation as requested


// this one doesn't filter the addresses -- I get the right customers, but I get all of their ad开发者_如何学运维dresses, 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;

Any ideas?


Based on the code above, it appears that you already have a rehydrated collection of Customer objects in the Customer variable.

You will need to call the Include function when you fill your Customer collection above. This way, the framework will rehydrate the included objects at the time of retrieval from your data context.

The actual query code appears good though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜