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
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)
{
}
}
}
{
"ConnectionStrings": {
"DefaultConnection": "Server=ASHISH\\SQLEXPRESS;Database=TestDB;Trusted_Connection=true;MultipleActiveResultSets=true;TrustServerCertificate=true;encrypt=false"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
We have to pass connectionString to ApplicationDbContext from Program.cs
var builder = WebApplication.CreateBuilder(args);
//passing connectionString to ApplicationDbContext class
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
DbSet corresponds to a table in the database
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; }
}
}
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. |
Steps: Tools->NuGet Package Manager->Package Manager Console -> write migration command ->Enter
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