Many-to-Many Relationships
A many-to-many relationship in SQL occurs when multiple records in one table are associated with multiple records in another table. To implement this, you typically use another table that connects the two.
This table is known by a few different names :
- Junction table
- Bridge table
- Linking table
- Associative table
- Mapping table
Technical Requirements
-
Two database tables acting with a parent child relationship, enforced with a FOREIGN KEY relationship.
-
A table in another database on the same SQL Server, which needs to act as the grandparent in the above relationship.
-
A grandparent can be assigned to many parents.
-
A parent can have many grandparents.
Solution
Data in the parent and child tables is currently maintained using one of my Reference Data Web Apps
These apps are configured by me to be per database, so that I have only one connection string in the settings file, to keep things clean and simple.
If I break convention and start to include tables from other databases, this will eventually lead to a bloated application as this quick and easy fix will always be more tempting than spinning up another reference data web app (despite my blog post above detailing how “quick and easy” it is).
Also, restricting the app to one database helps to manage authorised access to the data at the database level.
So to maintain this, I create a SQL VIEW to SELECT the records from the other database, and treat this as just another “table”/POCO in the dotnet web app.
|
The scaffolded entity for the grandparent VIEW resulted in a null reference exception when accessing the parent.
|
Simplifying it to the below resolved the error :
|
I declared the linking table as so:
|
The column names were not as I originally declared.
Scaffolding the table resulted in SQL errors about missing column names.
So I re-created the table using the column names that EF core was expecting.

And configure it within the EF model builder:
|
|
I am well impressed with how EF Core handled this scenario.