Code First Approach in ASP.NET Core MVC?
Code First is complete dynamic approach of entity framework where we create database configuration and table dynamically using dB Context class.
1) Create Web Project using ASP.NET Core MVC Project Template
2) Add Library from Nuget Package
EntityFrameworkCore.Design
EntityFrameworkCore.SQLServer
EntityFrameworkCore.Tools
3) Create Local Database using Server Explorer
4) Create Model Class Like this
using System.ComponentModel.DataAnnotations;
namespace WebApplication3.Models
{
public class Employee
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Mobileno { get; set; }
}
}
5) Create DbContext class
using Microsoft.EntityFrameworkCore;
namespace WebApplication3.Models
{
public class EmployeeDBContext:DbContext
{
public EmployeeDBContext(DbContextOptions<EmployeeDBContext> options)
: base(options) // The base(options) call passes the options to the base DbContext class constructor.
{
}
public DbSet<Employee> Employees { get; set; }
}
}
6) Create Connection String under appSettings.json
{
"ConnectionStrings": {
"MyDatabaseConnection": "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Shiva-PC\\Documents\\empdb.mdf;Integrated Security=True;Connect Timeout=30"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
7) Configure Connection String inder Program.cs
using Microsoft.EntityFrameworkCore;
using WebApplication3.Models;
builder.Services.AddDbContext<EmployeeDBContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MyDatabaseConnection"))
);
8) Open Nuget Package Manager Console
Add-Migration MigrationFileName
9) Update-Database
10) Create Controller with EntityFramework Scaffold Template
POST Answer of Questions and ASK to Doubt