Understanding Code First Approach Of Entity Framework Core
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.
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
Open Visual Studio. Click on File menu then New and the project.
Select Asp.Net Core project and click on Next button.
In next screen add Project Name and Project Location and click on Create button.
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.
Set up Entity Framework Core And Add new Table
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.
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.
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.
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.
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.
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.
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.
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.
Now open Package Manager Console by click on Tool Menu then NuGet Package Manager then Package Manager Console.
Add following command.
- Add-Migration Init
Here Init is our name of migration you can give as per your choice. Hit enter.
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.
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.
For now our database and table is not created for make changes in Server side use below command.
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.
Add New Column In Table
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.
Now execute below command. Here AddLanguageColumn is a name which I provide you can give as your choice.
- 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.
Now run below command to make changes in SQL server.
As you see in below image new column BookLanguage is add in my table Books.
Delete Column from Table
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.
Run below command
- 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.
Run below command to update database.
After executing above code you can see in below image that BookLanguage column is deleted from Books table.
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.
As see you see in below image just add MaxLength attribute on top of your property and specify your required size.
Run following command.
- Add-Migration AddColumnSize
Now you can see in your migration folder new file is generated and in that file there is code like below.
Now run below command to update changed in database.
As you seen in below image that our column now has size which we give in our code.
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.
Add required attribute on your property as shown in below image.
Now run the below command to add migration.
- 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.
Now run below command to save changes in database.
Now you can see in below image that our column is now not accept null value.
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.
Now you will see that your table is remove from your table.
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.
Add Key attribute on your column which you want to set as a primary column.
Run following command to add migration.
- 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.
Now run following command to update database
As you see in below image that now in our Employee table EmpId is primary key.
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.
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.
Now run below command to add migration.
- 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.
Run below command to Update Database.
As you see in below image that in sql server there is relationship add in employee table.
Deleting relationship is also easy just comment or remove Department type property from Employee table and that it.
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.
View on my official website : YogeshHadiya.In