Skip to content
Advertisement

Specifying a Many-to-many that handles two join tables (that previously handled many-to-manys) w/ entity framework core

I have never been in the situation where I originally had two many-to-many’s that were resolved. But then down another level is another many-to-many on both of those join tables. I am wondering if there is a better way to architect this w/ entity framework core. Here is what I got. I am trying to figure out which Project Owners are part of which Project Products.

I have 3 tables:

Project
Product
Owner

A Project can have many Products and a Project can have many Owners. A Product can have many Projects and an Owner can have many Projects. I resolved these two many-to-many relationships by doing the following:

ProjectProduct
Two keys: ProjectId, ProductId

ProjectOwner
Two keys: ProjectId, OwnerId

Additionally a ProjectProduct can have many ProjectOwners and a ProjectOwner can have many ProjectsProducts.

I thought the solution would be to add a unique Id to both ProjectOwner and ProjectProduct and create a new entity called ProjectProductOwner with the following keys:
ProjectProductId, ProjectOwnerId

Here is what my DBContext looks like:

I am getting the error: Introducing FOREIGN KEY constraint ‘FK_ProjectProductOwner_ProjectProducts_ProjectProductId’ on table ‘ProjectProductOwner’ may cause cycles or multiple cascade paths.

additionally:

‘FK_ProjectProductOwner_ProjectOwners_ProjectOwnerId’ on table ‘ProjectProductOwner’ may cause cycles or multiple cascade paths.

Advertisement

Answer

You can “merge” the ProjectProduct with the ProjectProductOwner into one table. Since you add Owners to the Project first, then you add one or more Products for each Owner in the Project I don’t see a need for a third many-to-many Entity, thus simplifying it a bit 🙂

Note: I didn’t even bother with the error, because as you said and I agree, most often these errors show up when your model isn’t correct.

Owner

Product

Project and many-to-many tables

DbContext configuration

Finally, you can add new projects and query it with something like this:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement