BlaShadow
BlaShadow

Reputation: 11703

How to Get data from many-to-many relation in Entity Framework?

I got 2 entities related to each other in a many-to-many relationship in my model.

There's just 2 tables I know that in the db there are 3 tables in SQL I may try something like this.

select * 
from table1 
where table1.id in (select idTable1 from middleTable)

How can I do this using Entity Framework and Linq?

Upvotes: 5

Views: 3852

Answers (2)

BlaShadow
BlaShadow

Reputation: 11703

I Resolve my problem with something like this

 container.Table.Where(x=> x.TableRealed.any(y=> x.column == value)).ToList()

Upvotes: 6

MgSam
MgSam

Reputation: 12813

If you're letting the Entity Designer generate your model for you, it can "hide" the "middle table" of many-to-many relationships, as long as that middle table contains nothing but the ids of the two tables that have the relationship (and those ids are primary keys).

Once the model has been generated, you will have collection properties on both "sides" of the relationship. For example, I have two tables, People and Houses, they have a many-to-many relationship. If I've set everything up correctly, each Person object will have a property Houses and each House object will have a property People.

Hope that makes sense.

Upvotes: 1

Related Questions