Introduction

In this article we will understand code first approach of Entity framework Core in ASP.Net Core. In this article we use entity framework core for creating table in SQL, delete table, update table, add columns, remove column etc.

Understanding code first approach of entity framework core - YogeshHadiya.in



In this article we cover following topic  

  • What Is Entity Framework Core?
  • Create New Asp.Net Core Project
  • Set up Entity Framework Core and Add new Table
  • Add New Column In Table
  • Delete Column from Table
  • Change Column Size
  • Make Column Not Null
  • Delete Table
  • Add Primary key Column
  • Add Relationship (Foreign Key)

 

What Is Entity Framework Core?

As per official website

Entity Framework Core is the new version of Entity Framework after EF 6.x. It is open-source, lightweight, extensible and a cross-platform version of Entity Framework data access technology.

Entity Framework is an Object/Relational Mapping (O/RM) framework. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database.

Create New Asp.Net Core Project

Step 1

Open Visual Studio. Click on File menu then New and the project.

Step 2

Select Asp.Net Core project and click on Next button.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Step 3

In next screen add Project Name and Project Location and click on Create button.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Step 4

In next window select .Net Core as a framework and version of framework. Here I choose empty template because in this project we just understand Code First approach of Entity Framework core, so there is no need to run project. You can choose template as per your requirement. Then click on Create button.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Set up Entity Framework Core And Add new Table

Step 1

Now our project is ready for work. First we have to add some NuGet packages for working with Entity Framework. Open NuGet package manager by right click on project name then click on Manage NuGet Package.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in


Step 2

Install the Following NuGet Packages. 

  • Microsoft.EntityFrameworkCore.SqlServer : This Package is use for interact with SQL Server from Our C# and .Net Core.
  • Microsoft.EntityFrameworkCore.Tools : This package is contained various command like Add-Migration, Drop-Database, Get-DbContext, Get-Migration, Remove-Migration, Scaffold-DbContext, Script-Migration, Update-Database. In this article we use Add-Migration and Upadate-Database command.
  • Microsoft.Extensions.Configuration : Using this NuGet package we can read data from our app setting file. We will get our connection string from the app setting file.

 

Step 3

Now we add a new folder in our solution to contain various classes. For adding new folder in our solution right click on project name the click on Add then click on New Folder and gave name as Model.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Step 4

In this Model folder we will use our entity classes. Right click in this folder then Add then Class. Give suitable name for your class. Here I gave book as my class name and add following properties as shown in below code.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in




Now add new class for Context class. Add Class and Extends this class from DbContext class. This class is in Microsoft.EntityFrameworkCore namespace so import this namespace.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in




Add constructor and add one parameter of DbContectOptions and also pass this parameter in base constructor by base keyword.

Create property of DbSet type of our Class which here is Book and gave suitable name.

Step 6

Now add connection string In app setting file.



As see in above code here I pass . (dot) as a server name because I used my local pc sql server. Then gave database name ASPNetCoreCodeFirst if this database not exist then it will generate automatically. Here I not give any username and password because I use windows authentication for this if you want to use other method to login then pass username and password.

Step 7

Now we have to add Db Context in our startup file for this open startup startup file and add following code. 



Here we create constructor with IConfiguration parameter. This Interface is in Microsoft.Extensions.Configuration namespace so import this namespace.

Then in ConfigureService Method we add our CFDbContext class and pass connection string in it by getting from our appsetting file using Configure.GetConnectionString() method.

Step 8

Now open Package Manager Console by click on Tool Menu then NuGet Package Manager then Package Manager Console.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Step 9

Add following command. 

  1. Add-Migration Init  

Here Init is our name of migration you can give as per your choice. Hit enter.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

As you can see in your solution new folder named Migration is created and in this project there is two file. One is CFDbContextModelSnapshot and other one is *_Init , here * mean date time stamp.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

In this init file there is below code. This code execute when we use our next command and it will generate new database and new table Called Books. 



 Step 10

For now our database and table is not created for make changes in Server side use below command. 

  1. Update-Database  
Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Now see in your server new database and new table called Books is created. By default when we pass property name as Id then it will automatically consider as primary key. So as you see in below image Id is primary key in our table. And string type data is convert as nvarchar and size of this is MAX.
Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Add New Column In Table

Step 1

For add new column in table add new property in your model. As you see in below image I add BookLanguage in my Book model.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Step 2

Now execute below command. Here AddLanguageColumn is a name which I provide you can give as your choice. 

  1. Add-Migration AddLanguageColumn  

 After executing above command new file is created in migration folder. As you see in below code that this is a c# code for add new column which convert into sql and we will get new column in our table.



Step 3

Now run below command to make changes in SQL server. 

  1. Update-Database  

As you see in below image new column BookLanguage is add in my table Books.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Delete Column from Table

Step 1

Delete column from table is simple in entity framework core you just need to remove that property or comment from your entity model. As you see in below image I comment out BookLnguage property.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Step 2

Run below command 

  1. Add-Migration RemoveLanguageColumn  

Using this command a new file is created in Migration folder. As you see in below code that our BookLanguage will drop when we update database.





Step 3

Run below command to update database.

  1. Update-Database  

After executing above code you can see in below image that BookLanguage column is deleted from Books table.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Change Column Size

As you see in above example our column size is max for nvarchar type. But when we have to specify size of column we can also specify in entity framework core by just simple one line of code.

Step 1

As see you see in below image just add MaxLength attribute on top of your property and specify your required size. 

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Step 2

Run following command.

  1. Add-Migration AddColumnSize  

Now you can see in your migration folder new file is generated and in that file there is code like below.



Step 3

Now run below command to update changed in database. 

  1. Update-Database  
As you seen in below image that our column now has size which we give in our code.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Make Column Not Null

By default in entity framework core nvarchar type column accept null value. But we can change it also by following steps.

Step 1

Add required attribute on your property as shown in below image.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in


Step 2

Now run the below command to add migration.

  1. Add-Migration MakeColumnNotNull  

A new file will generate now in your migration folder. And as you see in code there is nullable property is false. 



Step 3

Now run below command to save changes in database.

  1. Update-Database  

Now you can see in below image that our column is now not accept null value.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Delete Table

Delete table from database using entity framework core code first approach is so simple you have only remove or comment that table from context file and add migration and then update database.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Now you will see that your table is remove from your table.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Add Primary key

In entity framework core when you add any column with name of Id than it will automatically consider as primary key but then what you need to define other column as primary key. You can specify a primary key in your table by following steps.

Step 1

Add Key attribute on your column which you want to set as a primary column.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Step 2

Run following command to add migration. 

  1. Add-Migration AddPrimaryKeyInEmpTable  

Now you can see new file in your migration folder. As you seen in below code that now EmpId is consider as a primary key. 



tep 3

Now run following command to update database

  1. Update-Database  

As you see in below image that now in our Employee table EmpId is primary key.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Add Relationship (Foreign Key)

Adding relationship in table is quite easy in entity framework core. Here I create new model Department and gave two column DepartmentId and DepartmentName. To add relation of department in employee table you can follow below steps.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in
Step 1 

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Add two property as you show in above image. Here I create DepartmentId type of integer and a Department type of Department model which I create earlier. I’m also specify my column name in ForeignKey attribute on Department property. Reason behind adding this is your relationship will create without adding this attribute but in this process entity framework core generate new column which is primary key in our parent table. In case if your primary table has DepartmentId then it will add relationship in DepartmentId if exist or if not exist than it will generate it.

But in case your child table column name is DeptId and you want to add relationship with it. But if you run without specify that attribute than it will generate new column in Employee table DepartmentId and make relationship. But if you specify DeptId in ForeignKey attribute than it will generate relationship with Deptid column.

Step 2

Now run below command to add migration.

  1. Add-Migration ForeignKey  

As you see in your migration folder that new file generated and if you look at code that it will add relationship between Employee and Department table on DepartmentId column.



Step 3

Run below command to Update Database.

  1. Update-Database  

As you see in below image that in sql server there is relationship add in employee table.

Understanding Code First Approach Of Entity Framework Core - YogeshHadiya.in

Deleting relationship is also easy just comment or remove Department type property from Employee table and that it.

Conclusion

I hope you get some help from this article if you have any doubt or suggestion please add in comments. And also share this article with your friends. Thank you.