Code-First Approach in Entity Framework Core

Code-First Approach in Entity Framework Core

In Code-First approach you create the entity classes only. Then with migration commands the EF Core creates the database based on these entity classes.

To understand how the Code-First approach works. First create a new ASP.NET Core project and Install Entity Framework Core on it.

ASP.NET Core Project

In this project I will be dealing with a Company application that contains information about its employees, departments, etc.

Creating Entity & Context classes

Create a class Information.cs inside the Models folder. It will contain information about the company like company id, name, license, year of establishment and yearly revenue.

public class Information
    public int Id { get; set; }
    public string Name { get; set; }
    public string License { get; set; }
    public DateTime Establshied { get; set; }
    public decimal Revenue { get; set; }

Next create a Context class and name it CompanyContext.cs. Place it inside the Models folder.

public class CompanyContext : DbContext
    public DbSet<Information> Information { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        if (!optionsBuilder.IsConfigured)

Creating a Migration

With Migration you can create the database based on the Entity & Context classes. Inside the OnConfiguring() method, I have provided the connection string for the database. Here in this case the database name is company.

In Visual Studio, open NuGet Package Manager Console from Tools > NuGet Package Manager >Package Manager Console and enter the following command:

PM> add-migration CompanyDB

Or, you can do the same thing with dotnet CLI by executing the following command:

PM> dotnet ef migrations add CompanyDB

The command will create Migrations folder on your project.

migrations folder

Now create the database by executing the update-database command on the Package Manager Console:

PM> update-database –verbose

Or, you can run the dotnet CLI command to do the same thing:

PM> dotnet ef database update

The command will execute and will create the Company database which you can open and see on your SQL Server.

company database

Inserting a Record on the Table using EF Core

Now that my database is ready, let me insert a record on the Information table.

Add the following code on a Index Action of your Controller.

using (var context = new CompanyContext())
    var info = new Information()

Once the Action is called, the code will execute, and a new record is added to the Information table.

You can see the new record on the SQL Server.

record inserted


Share this article -



This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.