Sử dụng EF Core Code First trong .NET Core để tạo cơ sở dữ liệu

Đầu tiên, cài đặt các gói NuGet cần thiết:

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools

Khởi tạo hai lớp thực thể đại diện cho bảng trong cơ sở dữ liệu:

public class DonVi
{
    [Key]
    public int Ma { get; set; }
    public string MaCap { get; set; }
    public string TenDonVi { get; set; }
    public string PhimTat { get; set; }
    public int MaCha { get; set; }
    public string TenCha { get; set; }
    public bool LaLa { get; set; }
    public bool TuMoRong { get; set; }
    public string Icon { get; set; }
    public int TrangThai { get; set; }
    public int Loai { get; set; }
    public string MaKinhDoanh { get; set; }
    public string MaTuChon { get; set; }
    public DateTime ThoiGianTao { get; set; }
    public int NguoiTao { get; set; }
    public int ThuTu { get; set; }
}
public class VaiTro
{
    [Key]
    public int Ma { get; set; }
    public string TenVaiTro { get; set; }
    public int TrangThai { get; set; }
    public int Loai { get; set; }
    public DateTime ThoiGianTao { get; set; }
    public string NguoiTao { get; set; }
    public int MaDonVi { get; set; }
    public string MaDonViCap { get; set; }
    public string TenDonVi { get; set; }
}

Tạo lớp DbContext để quản lý các DbSet:

public class QuanLyDbContext : DbContext
{
    public QuanLyDbContext(DbContextOptions<QuanLyDbContext> options) : base(options) { }

    public DbSet<VaiTro> DanhSachVaiTro { get; set; }
    public DbSet<DonVi> DanhSachDonVi { get; set; }
}

Cấu hình chuỗi kết nối trong appsettings.json:

"ConnectionStrings": {
  "DefaultConnection": "Server=localhost;Database=DemoCodeFirst;User Id=sa;Password=mat_khau_cua_ban;"
}

Đăng ký DbContext vào container DI trong Program.cs:

builder.Services.AddDbContext<QuanLyDbContext>(options =>
{
    var connStr = builder.Configuration.GetConnectionString("DefaultConnection");
    options.UseSqlServer(connStr);
});

Nếu gặp lỗi: "Could not load assembly '...'", hãy đảm bảo dự án khởi động đang được chọn đúng trong Visual Studio.

Thực hiện lệnh migration để tạo cơ sở dữ liệu:

add-migration KhoiTaoBanDau
update-database

Thêm dữ liệu mẫu (seed data) sau khi tạo bảng:

public static class DuLieuMau
{
    public static async Task NapDuLieuAsync(IServiceProvider dichVu)
    {
        using var phamVi = dichVu.CreateScope();
        var dbContext = phamVi.ServiceProvider.GetRequiredService<QuanLyDbContext>();

        if (await dbContext.DanhSachVaiTro.AnyAsync()) return;

        dbContext.DanhSachVaiTro.Add(new VaiTro
        {
            TenVaiTro = "Quản trị viên",
            TrangThai = 1,
            Loai = 1,
            MaDonVi = 1,
            TenDonVi = "Phòng IT",
            MaDonViCap = "IT01",
            NguoiTao = "admin",
            ThoiGianTao = DateTime.Now
        });

        await dbContext.SaveChangesAsync();
    }
}

Gọi hàm seed trong pipeline ứng dụng (sau app.Run()):

using var scope = app.Services.CreateScope();
var services = scope.ServiceProvider;
var context = services.GetRequiredService<QuanLyDbContext>();
context.Database.EnsureCreated();
await DuLieuMau.NapDuLieuAsync(services);

Để vô hiệu hóa hành vi xóa theo cấp (cascade delete), ghi đè phương thức OnModelCreating:

protected override void OnModelCreating(ModelBuilder builder)
{
    var khoaNgoai = builder.Model.GetEntityTypes()
        .SelectMany(e => e.GetForeignKeys());

    foreach (var fk in khoaNgoai)
    {
        fk.DeleteBehavior = DeleteBehavior.Restrict;
    }
}

Lưu ý: Nếu DbContext nằm trong một dự án riêng biệt, khi chạy lệnh add-migration, cần chọn đúng dự án chứa DbContext trong Package Manager Console và dự án khởi động là nơi chứa Program.cs.

Thẻ: ef-core .NET-Core code-first

Đăng vào ngày 14 tháng 6 lúc 19:42