Entity Framework
Install Packages
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer
Add DI
builder.Services.AddDbContext<AppDBContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnectionString"))
);
Code First
Create Model
public class Item
{
public int ID { get; set; }
public string Title { get; set; }
}
Create DBContext Model
public class AppDBContext : DbContext
{
public AppDBContext(DbContextOptions<AppDBContext> options) : base(options) { }
public DbSet<Item> Items { get; set; }
}
Package Manager Console CMD
Add-Migration "Initial Migration"
Database First
Package Manager Console CMD
Scaffold-DbContext "Connection String" Microsoft.EntityFrameworkCore.SqlServer -ContextDir DataFolder -OutputDir Models -DataAnnotation
Usage
private readonly AppDBContext _context;