...
/Configuring Many-to-Many Relationships
Configuring Many-to-Many Relationships
Learn how to configure many-to-many relationships using default conventions, data annotations, and the fluent API.
We'll cover the following...
Overview
In this lesson, we’ll look at the conventions between two entities that result in a many-to-many relationship between their corresponding tables in the database. We’ll also look at how to supplement these conventions using data annotations and the fluent API.
Many-to-many relationships utilize a collection navigation property at both ends. In relational databases, a join table represents a many-to-many relationship in the database. This table includes the foreign keys of both tables.
Note: The commands in this lesson generate code and files. Through the terminal, we can navigate to these files by using relevant Linux commands such as
lsto view a list of files and directories),cdto change directories, andcatto view file contents. A SPA widget showing the updated project with the generated files is also available. Also, note that EF Core uses a timestamp within the generated file names. We represent these names withxxx.
Default conventions
By convention, when EF Core discovers a collection navigation property at both ends of entities, it creates an entity type internally to represent a join table. The entity type is called a join entity type. EF Core uses two one-to-many relationships on the join entity type to represent the many-to-many relationship.
We demonstrate configuring a many-to-many relationship using the C# project below:
{
"version": "0.2.0",
"configurations": [
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/net6.0/Relationships.dll",
"args": [],
"cwd": "${workspaceFolder}",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "internalConsole",
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
]
}Click the “Run” button ...