如何从实体框架的多对多关系中获取数据?

时间:2022-10-04 12:20:33

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.

我知道在数据库中只有2个表SQL中有3个表我可以试试这样的东西。

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

How can I do this using Entity Framework and Linq?

如何使用实体框架和Linq实现这一点?

2 个解决方案

#1


5  

I Resolve my problem with something like this

我用这样的方法来解决我的问题

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

#2


1  

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).

如果让实体设计器为您生成模型,那么它可以“隐藏”多对多关系的“中间表”,只要中间表只包含有关系的两个表的id(而这些id是主键)。

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.

希望是有意义的。

#1


5  

I Resolve my problem with something like this

我用这样的方法来解决我的问题

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

#2


1  

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).

如果让实体设计器为您生成模型,那么它可以“隐藏”多对多关系的“中间表”,只要中间表只包含有关系的两个表的id(而这些id是主键)。

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.

希望是有意义的。