Martin Doms
Martin Doms

Reputation: 8748

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.

Upvotes: 6

Views: 2262

Answers (2)

zeeshanhirani
zeeshanhirani

Reputation: 2350

yeah that is probably the best approach to give you cleaner experience on querying and for the inserting and updating you can always use the link table. Eventually, will not mention when, EF will support navigation properties with payload. I am glad people like the work. It honestly took 1 year to write the book.

Upvotes: 2

Adam Rackis
Adam Rackis

Reputation: 83358

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

Upvotes: 8

Related Questions