Code First Approach in ASP.NET CORE MVC


 How to implement Code First Approach in ASP.NET CORE MVC:-

Code First Approach is best for light-weight and smaller project in ASP.NET MVC Core, it is basically created to those developer who is not know about SQL. without SQL Server or any database package developer can create complete project.

Step 1 New Project

Once you have installed the Visual Studio 2019 and .Net Core 3.1 SDK, you can start building a new ASP.NET Core Application.

Step 2nd:-

Create a web app and From the Visual Studio select Create a new project. Select ASP.NET Core Web Application > Next.

Step 3rd:-

Give your project a name i.e. SampleCodeFirstExample and give your project a location where it’ll be saved and click Create.


 Install the NuGet Packages

From the Solution right click on dependency, select Manage NuGet Packages and Select the Browse tab, and then enter Microsoft.EntityFrameworkCore.SqlServer in the search box, select Latest Stable Version and Install.


Now, install Microsoft.EntityFrameworkCore.Tools as same as above steps.


Create Model and Context Classes:

Now, Add new class with name “Emp”, using Right-click the Models folder and select Add Class.

public class Emp


        public long empid { get; set; }

        public string empname { get; set; }

        public int salary { get; set; }

        public string designation { get; set; }



Right-click the Models folder and select Add > Class. Name the class MyDbContext and click Add and change code in MyDbContext.cs as following:

  public class MyDbContext:DbContext


        public MyDbContext(DbContextOptions<MyDbContext> options):base(options)



        public DbSet<Emp> emps { get; set; }



Connection string you need to write inside the appsetting.json file as follows:

 "ConnectionStrings": {

    "Conn": "Data Source=SHIVA-PC\\SQLEXPRESS;Initial Catalog=collegeerp;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;"



Register Connection String under Program.cs file


builder.Services.AddDbContext<MyDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Conn")));


Create Database using Migration Commmand

add-migration initialmigration


Write update database command



We can check MS-SQL Server and Check Database 


Add new column in table then add new property in model class

public int age{get;set;}


write followings commands for migration

add-migration addedColumnname

update-database assedColumnname

Post a Comment


POST Answer of Questions and ASK to Doubt

Post a Comment (0)