How to perform a many-to-many Linq query with Include in the EF
I don't know how to perform this query using Linq and the EF.
Imagine I have three tables A, B and C.
A and B have a many-to-many relationship. B and C have a 1-to-many relationship.
I want to obtain records from B including C but filtering from A's Id. I can get开发者_开发问答 easily the records from B:
var result = Context.A.Where(x => x.Id.Equals(aId)).SelectMany(x => x.B);
but when I try to include C I don't know how to do it:
//This doesn't work
var result = Context.A.Where(x => x.Id.Equals(aId)).SelectMany(x => x.B.Include("C"));
Also I've tried this with no luck (it is equivalent to the above):
//Not working
var result = (from a in Context.A.Where(x => x.Id.Equals(aId))
from b in a.B.Include("C")
select b);
Thanks for your help.
OK, I found the Any extension method...
This is the solution:
var result = (from b in Context.B.Include("C")
where b.A.Any(x => x.A.Equals(aId))
select b);
精彩评论