Search code examples
c#entity-frameworkmodelscontrollers

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). So in my DB it's correct, I have 3 tables (Person, Event and Booking) with many to many relationship. But I have only 2 models in Visual Studio (Booking doesn't exist because of the self-generated table). 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?


Solution

  • When you are using ORMs like EF, you can sit back and let the ORM manage these middle tables.

    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.

    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