Understanding Code First Approach Of Entity Framework Core
Understanding Code First Approach Of Entity Framework Core
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.
public class Book
{
public int Id { get; set; }
public string BookName { get; set; }
public string AuthorName { get; set; }
public int Price { get; set; }
}
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.
public class CFDbContext : DbContext
{
public CFDbContext(DbContextOptions options) :base(options)
{
}
DbSet<Book> Books { get; set; }
}
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.
{
"ConnectionStrings": {
"ConStr": "Server=.;Database=ASPNetCoreCodeFirst;MultipleActiveResultSets=True;Trusted_Connection=True;"
},
//Other Code
}
Step 7
Now we have to add Db Context in our startup file for this open startup startup file and add following code.
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CFDbContext>(x=>x.UseSqlServer(Configuration.GetConnectionString("ConStr")));
}
// Other 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.
using Microsoft.EntityFrameworkCore.Migrations;
namespace ASPNetCoreCodeFirst.Migrations
{
public partial class init : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Books",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
BookName = table.Column<string>(type: "nvarchar(max)", nullable: true),
AuthorName = table.Column<string>(type: "nvarchar(max)", nullable: true),
Price = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Books", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "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.
using Microsoft.EntityFrameworkCore.Migrations;
namespace ASPNetCoreCodeFirst.Migrations
{
public partial class AddLanguageColumn : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "BookLanguage",
table: "Books",
type: "nvarchar(max)",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "BookLanguage",
table: "Books");
}
}
}
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.
using Microsoft.EntityFrameworkCore.Migrations;
namespace ASPNetCoreCodeFirst.Migrations
{
public partial class RemoveLanguageColumn : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "BookLanguage",
table: "Books");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "BookLanguage",
table: "Books",
type: "nvarchar(max)",
nullable: true);
}
}
}
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.
using Microsoft.EntityFrameworkCore.Migrations;
namespace ASPNetCoreCodeFirst.Migrations
{
public partial class AddColumnSize : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "BookName",
table: "Books",
type: "nvarchar(50)",
maxLength: 50,
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(max)",
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "AuthorName",
table: "Books",
type: "nvarchar(50)",
maxLength: 50,
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(max)",
oldNullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "BookName",
table: "Books",
type: "nvarchar(max)",
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(50)",
oldMaxLength: 50,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "AuthorName",
table: "Books",
type: "nvarchar(max)",
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(50)",
oldMaxLength: 50,
oldNullable: true);
}
}
}
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.
using Microsoft.EntityFrameworkCore.Migrations;
namespace ASPNetCoreCodeFirst.Migrations
{
public partial class MakeColumnNotNull : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "BookName",
table: "Books",
type: "nvarchar(50)",
maxLength: 50,
nullable: false,
defaultValue: "",
oldClrType: typeof(string),
oldType: "nvarchar(50)",
oldMaxLength: 50,
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "AuthorName",
table: "Books",
type: "nvarchar(50)",
maxLength: 50,
nullable: false,
defaultValue: "",
oldClrType: typeof(string),
oldType: "nvarchar(50)",
oldMaxLength: 50,
oldNullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "BookName",
table: "Books",
type: "nvarchar(50)",
maxLength: 50,
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(50)",
oldMaxLength: 50);
migrationBuilder.AlterColumn<string>(
name: "AuthorName",
table: "Books",
type: "nvarchar(50)",
maxLength: 50,
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(50)",
oldMaxLength: 50);
}
}
}
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.
using Microsoft.EntityFrameworkCore.Migrations;
namespace ASPNetCoreCodeFirst.Migrations
{
public partial class AddPrimaryKeyInEmpTable : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Employees",
columns: table => new
{
EmpId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
EmpName = table.Column<string>(type: "nvarchar(max)", nullable: true),
EmpDesignation = table.Column<string>(type: "nvarchar(max)", nullable: true),
EmpSalary = table.Column<long>(type: "bigint", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Employees", x => x.EmpId);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Employees");
}
}
}
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.
using Microsoft.EntityFrameworkCore.Migrations;
namespace ASPNetCoreCodeFirst.Migrations
{
public partial class ForeignKey : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "DepartmentId",
table: "Employees",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateTable(
name: "Departments",
columns: table => new
{
DepartmentId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
DepartmentName = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Departments", x => x.DepartmentId);
});
migrationBuilder.CreateIndex(
name: "IX_Employees_DepartmentId",
table: "Employees",
column: "DepartmentId");
migrationBuilder.AddForeignKey(
name: "FK_Employees_Departments_DepartmentId",
table: "Employees",
column: "DepartmentId",
principalTable: "Departments",
principalColumn: "DepartmentId",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Employees_Departments_DepartmentId",
table: "Employees");
migrationBuilder.DropTable(
name: "Departments");
migrationBuilder.DropIndex(
name: "IX_Employees_DepartmentId",
table: "Employees");
migrationBuilder.DropColumn(
name: "DepartmentId",
table: "Employees");
}
}
}
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.