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.

This approach is helpful in situations where you are starting with the development of a new project and don’t have a clear picture of the database. To understand how the Code-First approach works, first create a new ASP.NET Core project and Install Entity Framework Core on it.

If you had worked with previous Entity Framework 6 then you would have used the Database-First approach and created EDMX file. The EDMX file contains snapshot of the database, it’s table, stored procedures, relationships, etc. Now the shift is mode to Code-First approach, in-fact Microsoft has placed heavy emphasis on the Code-First approach. You can say Database-First approach is all but dead.
ASP.NET Core Project

In this project I will be dealing with a Company informations like it’s employees, departments, etc.

Create 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.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CodeFirst.Models
{
    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 Database Context Class (DbContext) and name it CompanyContext.cs. Place it inside the Models folder.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace CodeFirst.Models
{
    public class CompanyContext : DbContext
    {
        public DbSet<Information> Information { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer(@"Server=vaio;Database=Company;Trusted_Connection=True;");
            }
        }
    }
}

Performing Migrations

With Migrations you can create the database based on the Entity & Database Context classes. Check that 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 to create a migration.

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 a Migrations folder on your project.

I have written complete tutorial on EF Core Migrations. You will find it very useful.
migrations folder

Now create the database by executing the update-database migration 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CodeFirst.Models;
using Microsoft.AspNetCore.Mvc;

namespace CodeFirst.Controllers
{
    public class HomeController : Controller
    {
        public string Index()
        {
            using (var context = new CompanyContext())
            {
                var info = new Information()
                {
                    Name = "YogiHosting",
                    License = "XXYY",
                    Revenue = 1000,
                    Establshied = Convert.ToDateTime("2014/06/24")
                };
                context.Information.Add(info);
                context.SaveChanges();
            }

            return "Record Inserted";
        }
    }
}

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

Download the source codes from here.

DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

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.