Setup one-to-many relationship with Entity Framework

Setup one-to-many relationship with Entity Framework

Original YouTube Logo

Article have related YouTube video

Entity Framework is a fantastic tool. Also to setup relationships in your database. In this article I will make you a champ to setup a one-to-many relationship by using Entity Framework.

07-04-2023 |

Entity Framework

To start with, I do believe you already have setup a DbContext file and have two tables that you want to create a one-to-many from.

In this example I have 2 tables with a one-to-many relationship. It is a comments table and a posts table. So imagine we have a blog with some posts and every post can have some comments. So a post can have many comments. But a comment can only be in one post. So now we have a one-to-many relationship

Lets go and take a look at the post model and the comment model:



So the way you create a one-to-many relationship is to say, which model can have multiple objects of the other table. In this case we know that a post can hold many comments. So we will go and add a ICollection with the specific model of what it can hold and then give it a proper variable name inside the Post class.

Then we want to go into the Comment.cs class to specify what this can hold 1 object of. First we do say that it can contain a PostId which is just a normal int. However the Comment class can also hold one Post. So we give it a property called Post that can hold a Post object.

When these things is specified we just need 1 more thing to tell entity framework that we actually want a one-to-many relationship. Inside your DbContext file, you want to add this code:

The cool thing about Entity Framework is that the code almost explains itself. However in the OnModelCreating method we can use the ModelBuilder to tell we want a one-to-many relationship. We want to use the entity of the Comment object. Then say it can have one Post, with many comments. The foreignkey should be PostId and that it is required so that a comment cant be created without being added to a post.

Finally we add the two table with DbSet. So now you can go a run the add-migration command and update the database.

Like what you see?

New C# Learning Area - Free!

Our website now offers a new section on C# theory, including code examples and related video tutorials.


Subscribe to ZetBits Newsletter