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.













Join the conversation! Your thoughts help the community grow.