In this article I am going to demonstrate how to configure one-to-may and many-to-many relationship using Entity Framework code first approach, by taking a rich example in asp.net MVC.
As you see in the above figure, we are going to configure One-to-Many relationship between Post and Category as many posts in one category and Many-to-Many relationship between Post and Tag entity classes via PostTagMap entity.
Entity Framework knows that there is a many-to-many relationship between two classes when two classes have collections of one another’s type.
Create Post class in Model folder:
Create Category class in the same Model folder:
Post entity class has reference property of Category class with CategoryID foreign key property and Category class has collection property for Posts. So this DataAnnotation will result in One-to-Many relationship.
Create Tag class in Model folder:
Post class should have collection navigation property for Tags and Tag should have collection navigation property for Posts which will create Many-to-Many relationship between post and tag.
Create PostDbContext class to create entities in database and configuring many-to-many relationship using fluent API.
As you can see in above code that we are mapping left key (key column of Post class) with “PostID” and right key (key column of Tag class) with “TagID” of table “PostTagMap”.
This will create new joining table “PostTagMap” with two primary key (composite key) which is also foreign key of Post and Tag table.
Create PostDbContextInitializer class to insert some sample data in order to test our application:
Create a PostModel class in Model folder:
Create a HomeController in controller folder and edit the code as given below:
Add a _Layout.cshtml in Views/Shared folder and replace the code as given below:
Add a Index view and replace the code with following:
Do not forget to add a connection string in web.config before running an application because entity framework finds the connection string with the name PostDbContext.
To learn more about entity framework code first. Refer this link.
Now run an application to test it. It will something look like below if everyting is ok.
You can ask any question if you find something during reading or implementation of this post.
Thanks for reading this article. Please can give your valuable comments and like if you find this helpful for you.