简体   繁体   English

具有多对多关系生成表的实体框架

[英]Entity Framework with many to many relationship generetad tables

Here's my question. 这是我的问题。 I have 2 models (Person, Event) and with EF and modelbuilder I generate a booking table (with IdPerson and IdEvent as properties). 我有2个模型(人员,事件),并使用EF和modelbuilder生成一个预订表(以IdPerson和IdEvent作为属性)。 So in my DB it's correct, I have 3 tables (Person, Event and Booking) with many to many relationship. 因此,在我的数据库中,这是正确的,我有3个表(人,事件和预订),并且具有多对多关系。 But I have only 2 models in Visual Studio (Booking doesn't exist because of the self-generated table). 但是我在Visual Studio中只有2个模型(由于自生成表,因此预订不存在)。 With my Controller I want to write an action for the Person to suscribe to an event and I have to write on my table Booking on the DB but it doesn't exist as a model so I can't do that . 对于我的控制器,我想写一个动作让那个人订阅一个事件,我必须在我的桌子上写“在数据库上的预订”,但是它不作为模型存在,所以我不能这样做。 How should I proceede? 我应该如何进行? Should I create a Booking model and delete my modelbuilder? 我应该创建一个预订模型并删除我的模型构建器吗?

I assume this is a model first approach. 我认为这是模型优先的方法。

The reason for having only 2 objects is that, by default, EF does not create objects for joint tables. 仅具有2个对象的原因是,默认情况下,EF不会为联合表创建对象。 What it does create is Navigation Property ( Entity Framework - Navigation Property Basics ). 它确实创建的是导航属性( Entity Framework-导航属性基础 )。 In one-to-many scenario, a navigation property inside a parent object contains a collection of entities in a foreign / child table. 在一对多情况下,父对象内的导航属性包含外部/子表中的实体的集合。 In many-to-many scenario, navigation properties of each entities will simply contain collections of its other entities. 在多对多方案中,每个实体的导航属性将仅包含其其他实体的集合。

When you are using ORMs like EF, you can sit back and let the ORM manage these middle tables. 当使用像EF这样的ORM时,您可以坐下来让ORM管理这些中间表。

You can use 您可以使用

person.Events.Add(event)

or 要么

event.People.Add(event)

and EF handles all and inserts a row with personId and eventId in that table. EF处理所有内容,并在该表中插入包含personIdeventId的行。

Here you can find a complete sample: http://blogs.msdn.com/b/wriju/archive/2011/05/14/code-first-ef-4-1-building-many-to-many-relationship.aspx 在这里您可以找到完整的示例: http//blogs.msdn.com/b/wriju/archive/2011/05/14/code-first-ef-4-1-building-many-to-many-relationship。 aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM