Content

  • Creating ApplicationDbContext class
  • Setting up connectionString in appSettings.json
  • Passing connectionString to ApplicationDbContext
  • Adding DbSet to ApplicationDbContext
  • Database Migration
  • Migration Commands
  • Updating Database with Migration

Creating ApplicationDbContext class

Create folder - "Data" -> Right click on folder -> Add -> New Empty File -> ApplicationDbContext.cs

ApplicationDbContext class must be inhereted from DbContext

We have to crate constructor of ApplicationDbContext to establish connection with database

Example:

ApplicationDbContext.cs File

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
                    
namespace Test.Web.Data
{
    public class ApplicationDbContext : DbContext
    {
        //creating constructor
        public ApplicationDbContext(DbContextOptions options):base(options)
        {
            
        }  
    }
}

Setting up connectionString in appSettings.json

Example:

appSettings.json File

{
"ConnectionStrings": {
    "DefaultConnection": "Server=ASHISH\\SQLEXPRESS;Database=TestDB;Trusted_Connection=true;MultipleActiveResultSets=true;TrustServerCertificate=true;encrypt=false"
},
"Logging": {
    "LogLevel": {
    "Default": "Information",
    "Microsoft.AspNetCore": "Warning"
    }
},
"AllowedHosts": "*"
}

Passing connectionString to ApplicationDbContext

We have to pass connectionString to ApplicationDbContext from Program.cs

Example

Program.cs File

var builder = WebApplication.CreateBuilder(args);
//passing connectionString to ApplicationDbContext class
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

Adding DbSet to ApplicationDbContext

DbSet corresponds to a table in the database

Example:

ApplicationDbContext.cs File

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
                    
namespace Test.Web.Data
{
    public class ApplicationDbContext : DbContext
    {
        //creating constructor
        public ApplicationDbContext(DbContextOptions options):base(options)
        {
            
        }
        
        //adding DbSet
        public DbSet<Students> Students { get; set; }
    }
}

Database Migration

  • Database migration in Entity Framework Core refers to the process of changing the database schema (structure) to match changes in the application's data model.
  • To perform migration, we have to install - Microsoft.EntityFrameworkCore.Tools Packge
  • Right click on Project Name -> Manage NuGet Packages -> Search - Microsoft.EntityFrameworkCore.Tools -> Select Version - 7.0.11 -> Install

Migration Commands

We can perform Migrations through Package Manager Console

Command Description
add-migration MigrationName Creates a new migration based on the changes detected in your DbContext.
update-database Applies any pending migrations to the database, updating its schema to match the current model.
remove-migration Removes the last migration snapshot and reverts the model snapshot to the previous one.
get-migrations Lists all migrations that have been applied or haven't been applied yet.
script-migration Generates a SQL script instead of applying migrations directly to the database.

Updating Database with Migration

Steps: Tools->NuGet Package Manager->Package Manager Console -> write migration command ->Enter

Example:

PM> add-migration initial
Build started...
Build succeeded.
To undo this action, use Remove-Migration.

After executing above commands, "Migrations" folder will be created in Project

To update database with this migration we can exexute below command

PM> update-database