开发者

How to perform a many-to-many Linq query with Include in the EF

开发者 https://www.devze.com 2022-12-26 18:27 出处:网络
I don\'t know how to perform this query using Linq and the EF. Imagine I have three tables A, B and C.

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);
0

精彩评论

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