Entity Framework Core With the Code First Approach in .Net Core Project

Enes Gür
The Startup
Published in
6 min readOct 16, 2020

In this article, I will talk about how to building-related tables in MSSQL on the .Net Core application with Entity Framework Core, which is a powerful ORM tool that I used it fondly for a while with the Code First approach.

I am going to explain “What is the ORM”, “What is the Entity Framework and its advangates”, “What is the Code First approach”, “How to build related tables with Entity Frame Core in .Net Core project in a sample application”.

What is the ORM

ORM(Object Relational Mapping) is a technology that convert models to our database tables, properties to columns, objects to a records in the database. ORM tools allows perform database operations for us so we can perform database operations on classes and objects.

As we can see in the picture, ORM makes mapping between OOP and database, It provides us with the convenience of application development in relational databases without dealing with database structures and queries.

What is the Entity Framework

Entity Framework is a .Net based ORM tool developed by Microsoft. Entity Framework is a tool that is a bridge between the application and the database.

Entity Framework contains 3 different methods:

  • Model First Method
  • Database First Method
  • Code First Method

In this post, we will do sample application with Code First Method.

The advantages of Entity Framework:

  • There is no database dependency.
  • It has a flexible usage.
  • It can be switched between database management systems, for example, the database created in MS-SQL can be moved to PL-SQL.

What is the Code First Approach

It is an approach that we perform database operations by writing code. It is created by coding all transactions related to the database. In this approach the power is on the developer :)

Now we can move to build a sample application.

Building Related Tables with Entity Framework Core in .Net Core Project in a Sample Application

We are creating a solution and adding 2 projects (default API and default ClassLibrary) under the solution. My .Net Core version is 3.1.

We will realize our scenario through a “Basketball Application”. The application will have classes that will include different relationships (1:1), (1:m), (m:m)

First of all, we should add Entity Framework Core libraries which we need, from Nuget to our project. We will run these commands in Package Manager Console but be sure that Default project section must be “EfCoreRelations.Data”

  • Install-Package Microsoft.EntityFrameworkCore -Version 3.1.9
  • Install-Package Microsoft.EntityFrameworkCore.SqlServer
  • Install-Package Microsoft.EntityFrameworkCore.Relational

And then we are adding these libraries for Api layer. Be sure that Default project section must be “EfCoreRelations.Api”

  • Install-Package Microsoft.EntityFrameworkCore -Version 3.1.9
  • Install-Package Microsoft.EntityFrameworkCore.SqlServer
  • Install-Package Microsoft.EntityFrameworkCore.Tools

According to our scenario, we will have six classes which are “Team”, ”Coach”, ”Country”, ”League”, ”Player”, ”TeamLeague”.

We will creating them in “Data” layer in “Models” folder.

  • one to one relationship

We will build a one to one relationship between “Team” and “Coach”. A team has only a coach and a coach works only in a team. We are setting our “Team” and “Coach” classes as follows:

Team.cs & Coach.cs

After we configured our classes like this, I will pass to explanation.

In “Team” class, I added “Coach” property to refer to “Coach” class and I did same in “Coach” class too but I decided to keep Foreign Key in “Coach” class. Foreign Key is “TeamId” property in “Coach” class.

This is a one to one relation and I have to do some configurations for mapping in both classes

In Team class:

builder.Property(x => x.TeamName).HasColumnType(“nvarchar(50)”); Defining column type as “nvarchar(50)”of “TeamName” because default is “nvarchar(MAX)”

builder.HasOne(x => x.Coach)Choosing “Coach” property in “Team” class
.WithOne(x => x.Team) → Connecting “Coach” property with “Team” property in “Coach” class
.HasForeignKey<Coach>(x => x.TeamId); → Defining a Foreign Key “TeamId” in “Coach” class

  • one to many relationship

We will build a one to many and many to one relationships between “Team-Country” and “Team-Player”. A team has a country but a country may have many teams. A team may have many players but a player plays only in a team. We are setting our Team, Player and Country classes like this

Team.cs
Country.cs & Player.cs

For relationship between “Team” and “Country”, I added “Country” property and “CountryId” property for Foreign Key. I configured mapping in “one” side in relationship so I made a configuration in “Team class”. As we can see in 33.line, I marked as a one to many relationship with “WithMany” keyword.

And for relationship between “Team” and “Player”, I added “Team” property and “TeamId” property (for Foreign Key) in “Player” class and configured mapping in that class.

  • many to many relationship

For this relationship, I have “Team” and “League” classes. A team may play in many leagues and a league may have many teams.

TeamLeague.cs
League.cs
Team.cs

I built many to many relationship between “Team” and “League” classes through “TeamLeague” class.

And we are adding DbContext to our applications for creating a bridge between OOP and Database

BasketballDbContext.cs

Now we will make migration from package manager console to create related tables according to my classes. Before migration, we should create database on SQL Server and adding its connection string to appsetting.json file like this as follows:

appsettings.json

and we will connect our database to our application in startup.cs as follows:

Startup.cs

Now we are ready for migration. We should open Package Manager Console in project and adding first migration with this command but be sure that Default project is EfCoreRelations.Data

→ add-migration Initial_Migration

After adding migration, if we can see “Migrations” folder in Data layer, that means everything is okay :) Now will update database with this command

→ update-database

Now we can check database for tables and diagram

We designed and created tables with Code First approach in .Net Core with Entity Framework Core.

You can access codes of project here.

Hope to see you in the next post, I wish you healthy days.

Resources

--

--