Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many-to-many relationships in Entity Framework where join table has more than two fields?

I am importing a database into Entity Framework and I'm having trouble with a many-to-many relationship that looks like this:

My understanding is that if the "join table" (the middle one) contains only two fields (the foreign keys) then EF will automatically remove the middle table and create a many-to-many relationship. Unfortunately I don't have control over the database schema, so does anyone know if there's a way to replicate that behaviour manually?

For the record, there is no purpose behind that Id field in Employee_Employee_Type, it's just poorly designed.

like image 990
Martin Doms Avatar asked Feb 15 '11 01:02

Martin Doms


People also ask

How does Entity Framework handle many-to-many relationships?

To configure many-to-many relationship Using Data Annotations, you need to create the Join Table in the model. The Join Table BookCategory will have properties for the primary key of both the table. It will have two navigational properties one each for Book and Category class.

Can a table have a many-to-many relationship with itself?

A self-referencing many-to-many relationship exists when a given record in the table can be related to one or more other records within the table and one or more records can themselves be related to the given record.


1 Answers

According to Entity Framework 4 recipes, page 554, this is how you'd do it (it's not pretty).

Essentially, you want to create a View of the Employee_Employee_type mapping table, but without the extra column, then manually map it to the other two tables. Below are pics of the relevant pages. I think (and hope!) this is covered by academic free-use copyright laws...

The book is fantastic, BTW, so I'd recommend buying it. Hopefully that will endear me to the author if he happens upon this.

enter image description here

enter image description here

like image 151
Adam Rackis Avatar answered Nov 07 '22 01:11

Adam Rackis