Introduction
In this article, we will learn the code-first approach of Entity Framework Core in ASP.NET Core. In this article, we will use entity framework core for creating the table in SQL, deleting the table, updating the table, adding columns, removing columns, etc.
In this article, we cover the following topics:
- 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 the 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 the File menu > New > project.
Step 2
Select ASP.NET Core project and then click on the Next button.
Step 3
In the next screen add Project Name, Project Location then click on the Create button.
Step 4
In the next window select .Net Core as a framework and version of the framework.
Here I chose an empty template because in this project we will just understand the Code First approach of Entity Framework core so there is no need to run the project. You can choose a template as per your requirement. After that click on the Create button.
Set up Entity Framework Core And Add New Table
Step 1
Now our project is read. First of all, we will add some NuGet packages for working with Entity Framework. Open NuGet package manager by right click on the project name then click on the Manage NuGet Package.
Step 2
Install the following NuGet packages,
- Microsoft.EntityFrameworkCore.SqlServer - This Package is used to interact with SQL Server from Our C# and .Net Core.
- Microsoft.EntityFrameworkCore.Tools - This package contains various commands like Add-Migration, Drop-Database, Get-DbContext, Get-Migration, Remove-Migration, Scaffold-DbContext, Script-Migration, Update-Database. In this article, we will use Add-Migration and Update-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 will add a new folder in our solution to contain various classes. For adding a new folder in our solution we need to right-click on project name > Add > New Folder and gave the name as Model.
Step 4
In this Model folder, we will use our entity classes. Right-click in this folder > Add > Class. Give a suitable name for your class. Here I gave the book as my class name and added the following properties as shown in the 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 a new class for the Context class. Add Class and Extends this class from DbContext class. This class is in Microsoft.EntityFrameworkCore namespace so it imports this namespace.
public class CFDbContext : DbContext
{
public CFDbContext(DbContextOptions options) :base(options)
{
}
DbSet<Book> Books { get; set; }
}
Add constructor and add one parameter of DbContextOptions and also pass this parameter in the base constructor by base keyword.
Create a property of DbSet type of our Class(which is here the Book) and gave the suitable name.
Step 6
Now add a connection string in the app setting file,
{
"ConnectionStrings": {
"ConStr": "Server=.;Database=ASPNetCoreCodeFirst;MultipleActiveResultSets=True;Trusted_Connection=True;"
},
//Other Code
}
As see in the above code here I pass. (dot) as a server name because I used my local pc SQL server. Then give database name ASPNetCoreCodeFirst if this database does not exist then it will generate automatically. Here I am not giving any username and password because I am using windows authentication for this if you want to use another method to login then pass the username and password.
Step 7
Now we have to add Db Context in our startup file for this open startup file and add the 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
}
Here we will create a constructor with the IConfiguration parameter. This Interface is in Microsoft.Extensions. We import this namespace.
Then in ConfigureService Method we add our CFDbContext class and pass connection string in it by getting our appsetting file using Configure.GetConnectionString() method.
Step 8
Now open Package Manager Console by clicking on the Tool Menu then NuGet Package Manager and then Package Manager Console.
Step 9
Add the 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 a new folder named Migration is created and in this project, there are two files. One is CFDbContextModelSnapshot and another one is *_Init , here * with a mean date time stamp.
In this init file there is the below code. This code executes when we use our next command and it will generate a new database and a 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");
}
}
}
Step 10
For now, our database and table are not created to make changes on the Server-side, use the below command to do that,
- Update-Database
Now you can see in your server a new database and a new table called Books is created. By default when we pass property name as Id then it will automatically consider as the primary key.
So as you see in the below image Id is the primary key in our table. And string type data is converted as nvarchar and the size of this is MAX.
Add New Column In Table
Step 1
To add a new column in the table add a new property in your model. As you see in the below image I add BookLanguage in my Book model.
Step 2
Now execute the below command. Here AddLanguageColumn is a name which I am providing you can give as per your choice.
Add-Migration AddLanguageColumn
After executing the above command a new file is created in the migration folder. As you can see in the below code that this is a C# code for adding a new column that converts into SQL and we will get a 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");
}
}
}
Step 3
Now run the below command to make changes in the SQL server.
- Update-Database
As you see in the below image new column BookLanguage is added to my table Books.
Delete Column from Table
Step 1
Deleting a column from the table is simple in entity framework core you just need to remove that property or comment from your entity model. As you can see in the below image I comment out BookLanguage property.
Step 2
Run the below command,
Add-Migration RemoveLanguageColumn
Using this command a new file is created in the Migration folder. As you can see from the below code that our BookLanguage will drop when we update the 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);
}
}
}
Step 3
Run the below command to update the database.
Update-Database
After executing the above code you can see in the below image that the BookLanguage column is deleted from Books table.
Change Column Size
As you see in the above example our column size is maxed for nvarchar type. But when we have to specify the size of the column we can also specify in entity framework core by just one line of code.
Step 1
As you can see below the image, you need to add the MaxLength attribute on top of your property and specify your required size.
Step 2
Run the following command,
Add-Migration AddColumnSize
Now you can see in your migration folder the new file is generated and in that file there is the code which looks 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 the below command to update changes in the database.
Update-Database
As you have seen below the image that our column now has a size which we gave in our code.
Make Column Not Null
By default in entity framework core, nvarchar type column accepts a null value. But we can change it also by the following steps,
Step 1
Add required attributes on your property as shown in the 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 can see in the code there is a nullable property that 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);
}
}
}
Step 3
Now run the below command for saving changes in the database,
Update-Database
Now you can see in the below image that our column is now not accepted a null value.
Delete Table
Delete table from database using entity framework core code first approach is so simple you have to remove or comment that table from context file, add migration and then update the database.
Now you can see that your table is removed from your database.
Add Primary key
In the entity framework core when you will add any column with the name of Id then it will automatically consider as the primary key but then you need to define other columns as the primary key. You can specify the primary key in your table by following the steps,
Step 1
Add Key attribute on your column which you want to set as a primary column.
Step 2
Run the following command to add a migration,
Add-Migration AddPrimaryKeyInEmpTable
Now you can see the new file in your migration folder. As you have seen the below code that now EmpId is considered 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");
}
}
}
Step 3
Now run the following command to update the database,
Update-Database
As you can see in the below image that now in our Employee table EmpId is the primary key.
Add Relationship (Foreign Key)
Adding relationships in tables is quite easy in the entity framework core. Here I am creating a new model Department and giving two-column DepartmentId and DepartmentName. To add-relation of the department in the employee table, you can follow the below steps,
Step 1
We added two properties as you can see in the above image. Here I created a DepartmentId type of integer and a Department type of Department model which I created earlier. I also specify my column name in the ForeignKey attribute on the Department property. The reason behind adding this is your relationship will create without adding this attribute but in this process entity framework core generate a new column which is the primary key in our parent table. In case your primary table has DepartmentId then it will add a relationship in DepartmentId if it exists or if not then it will generate it.
But in case your child table column name is DeptId and you want to add a relationship with it, if you run without specifying that attribute then it will generate a new column in Employee table DepartmentId and make the relationship. But if you specify DeptId in the ForeignKey attribute then it will generate a relationship with the Deptid column.
Step 2
Now run the below command to add a migration,
Add-Migration ForeignKey
As you can see in your migration folder that new file is generated and if you look at the code that it will add a relationship between Employee and Department table on the 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");
}
}
}
Step 3
Run the below command to Update the Database,
Update-Database
As you see in the below image that in SQL Server there is a relationship added in the employee table.
Deleting relationships is also very easy we can comment or remove Department type property from the Employee table and that's it.
Conclusion
I hope you learned from this article if you have any doubt or suggestion please add in the comments. And also share this article with your friends. Thank you.