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.
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.
Step 3
In next screen add Project Name and Project Location and click on Create button.
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.
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.
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.
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.
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.
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.
Step 7
Now we have to add Db Context in our startup file for this open startup startup file and add following code.
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.
Step 9
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.
- Update-Database
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
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.
Step 2
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.
- Update-Database
As you see in below image new column BookLanguage is add in my table Books.
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.
Step 2
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.
- 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.
Step 1
As see you see in below image just add MaxLength attribute on top of your property and specify your required size.
Step 2
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.
Step 3
Now run below command to update changed in database.
- Update-Database
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.
Step 2
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.
- Update-Database
Now you can see in below image that our column is now not accept null value.
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.
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.
Step 1
Add Key attribute on your column which you want to set as a primary column.
Step 2
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
- 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.
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.
- 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.
- 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.
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.
0 Comments