Entity Framework Core (EF Core) là ORM của .NET: ánh xạ lớp C# thành bảng, truy vấn bằng LINQ và tạo bảng bằng migration. Bài này kết nối SQL Server hoặc MySQL và dùng scaffolding để sinh trang CRUD.

70 phútTrung cấp
Bạn sẽ học được
  • Cài EF Core và tạo DbContext
  • Cấu hình chuỗi kết nối
  • Tạo bảng bằng migration
  • Truy vấn bằng LINQ, sinh CRUD tự động

Cơ sở lý thuyết

Entity Framework Core (EF Core) là ORM chính thức của .NET: ánh xạ lớp C# (entity) thành bảng, viết truy vấn bằng LINQ (Language Integrated Query – truy vấn tích hợp ngôn ngữ, được kiểm tra kiểu khi biên dịch) và EF Core dịch sang SQL của CSDL cụ thể (SQL Server, PostgreSQL, MySQL, SQLite).

  • DbContext đại diện một phiên làm việc với CSDL, theo mẫu Unit of Work: theo dõi các thay đổi trên entity và ghi tất cả trong một giao dịch khi gọi SaveChanges().
  • DbSet<T> đại diện một bảng.
  • Code First: viết lớp trước, migration sinh CSDL; Database First: sinh lớp từ CSDL có sẵn (scaffold).
  • Quy ước (convention): thuộc tính Id là khóa chính, thuộc tính KhoaId + Khoa là khóa ngoại; tùy biến bằng Data Annotations hoặc Fluent API.
  • Theo dõi thay đổi tốn bộ nhớ: dùng AsNoTracking() cho truy vấn chỉ đọc. Nạp dữ liệu liên quan bằng Include() để tránh vấn đề N+1.
  • Truy vấn LINQ được tham số hóa nên an toàn trước SQL injection.

Cài đặt

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
# MySQL: dotnet add package Pomelo.EntityFrameworkCore.MySql
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet tool install --global dotnet-ef

DbContext và cấu hình

// Data/QlsvContext.cs
using Microsoft.EntityFrameworkCore;
public class QlsvContext(DbContextOptions<QlsvContext> options) : DbContext(options)
{
    public DbSet<SinhVien> SinhViens => Set<SinhVien>();
}

// appsettings.json
"ConnectionStrings": { "Qlsv": "Server=localhost;Database=qlsv;Trusted_Connection=True;TrustServerCertificate=True" }

// Program.cs
builder.Services.AddDbContext<QlsvContext>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("Qlsv")));

Migration

dotnet ef migrations add KhoiTao
dotnet ef database update

Truy vấn bằng LINQ

public class SinhVienController(QlsvContext db) : Controller
{
    public async Task<IActionResult> Index(string? q)
    {
        var ds = db.SinhViens.AsQueryable();
        if (!string.IsNullOrEmpty(q)) ds = ds.Where(s => s.Ten.Contains(q));
        return View(await ds.OrderByDescending(s => s.Diem).ToListAsync());
    }
}

Trong Visual Studio, chuột phải thư mục Controllers > Add > New Scaffolded Item > "MVC Controller with views, using Entity Framework" để sinh đủ trang thêm, sửa, xóa.

Ứng dụng thực tế

Bài toán: CSDL quản lý khoa và sinh viên (quan hệ một–nhiều), thống kê số sinh viên và điểm trung bình theo khoa bằng LINQ – EF Core dịch thành một câu SQL GROUP BY:

public class Khoa { public int Id { get; set; } public string Ten { get; set; } = "";
                    public List<SinhVien> SinhViens { get; set; } = []; }
public class SinhVien { public int Id { get; set; } [MaxLength(10)] public string Ma { get; set; } = "";
                        public string HoTen { get; set; } = ""; public double DiemTB { get; set; }
                        public int KhoaId { get; set; } public Khoa Khoa { get; set; } = null!; }

public class AppDbContext(DbContextOptions<AppDbContext> o) : DbContext(o)
{
    public DbSet<Khoa> Khoa => Set<Khoa>();
    public DbSet<SinhVien> SinhVien => Set<SinhVien>();
    protected override void OnModelCreating(ModelBuilder mb) =>
        mb.Entity<SinhVien>().HasIndex(s => s.Ma).IsUnique();
}

var thongKe = await db.SinhVien.AsNoTracking()
    .GroupBy(s => s.Khoa.Ten)
    .Select(g => new { Khoa = g.Key, SoSV = g.Count(), DiemTB = g.Average(s => s.DiemTB) })
    .OrderByDescending(x => x.DiemTB)
    .ToListAsync();
dotnet tool install --global dotnet-ef
dotnet ef migrations add KhoiTao
dotnet ef database update
Mẹo hay

Đối tượng DbContext được cung cấp qua Dependency Injection: chỉ cần khai báo tham số trong hàm khởi tạo controller.

Thực hành
  1. Tạo CSDL qlsv bằng migration.
  2. Hiển thị danh sách từ CSDL, có ô tìm kiếm.
  3. Sinh trang CRUD bằng scaffolding và chạy thử.
Tóm tắt bài học
  • EF Core = ORM của .NET.
  • DbContext + DbSet ánh xạ bảng.
  • migrations add, database update; truy vấn bằng LINQ.