Entity Framework Core cơ bản
Ghi nhớ nhanh
Phần tiêu đề “Ghi nhớ nhanh”EF Core là ORM giúp thao tác database bằng C# object. Code First thường bắt đầu từ entity class, rồi tạo migration để cập nhật database.
Cú pháp
Phần tiêu đề “Cú pháp”public class AppDbContext : DbContext{ public DbSet<Product> Products => Set<Product>();
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }}
public class Product{ public int Id { get; set; } public string Name { get; set; } = ""; public decimal Price { get; set; }}Lệnh thường dùng
Phần tiêu đề “Lệnh thường dùng”dotnet ef migrations add InitialCreatedotnet ef database updatedotnet add package Microsoft.EntityFrameworkCore.SqlServerdotnet add package Microsoft.EntityFrameworkCore.DesignVí dụ CRUD
Phần tiêu đề “Ví dụ CRUD”// Createdb.Products.Add(new Product { Name = "Mouse", Price = 150000 });await db.SaveChangesAsync();
// ReadList<Product> products = await db.Products.ToListAsync();
// UpdateProduct? product = await db.Products.FindAsync(1);if (product is not null){ product.Price = 120000; await db.SaveChangesAsync();}
// Deleteif (product is not null){ db.Products.Remove(product); await db.SaveChangesAsync();}Relationship cơ bản
Phần tiêu đề “Relationship cơ bản”public class Order{ public int Id { get; set; } public List<OrderItem> Items { get; set; } = new();}
public class OrderItem{ public int Id { get; set; } public int OrderId { get; set; } public Order Order { get; set; } = null!;}Cấu hình connection string
Phần tiêu đề “Cấu hình connection string”{ "ConnectionStrings": { "Default": "Server=.;Database=ShopDb;Trusted_Connection=True;TrustServerCertificate=True" }}builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));Query hay dùng
Phần tiêu đề “Query hay dùng”Product? product = await db.Products.FindAsync(id);
List<Product> cheapProducts = await db.Products .Where(p => p.Price < 100000) .OrderBy(p => p.Name) .AsNoTracking() .ToListAsync();Include relationship
Phần tiêu đề “Include relationship”Order? order = await db.Orders .Include(o => o.Items) .FirstOrDefaultAsync(o => o.Id == id);Tracking
Phần tiêu đề “Tracking”| Cách | Khi dùng |
|---|---|
| Tracking mặc định | Cần update/delete entity |
AsNoTracking() | Chỉ đọc dữ liệu, nhanh hơn |
Projection Select | Chỉ lấy cột cần thiết |
var productDtos = await db.Products .AsNoTracking() .Select(p => new ProductDto(p.Id, p.Name)) .ToListAsync();
public record ProductDto(int Id, string Name);Migration workflow
Phần tiêu đề “Migration workflow”dotnet ef migrations add AddProductPricedotnet ef database updatedotnet ef migrations listdotnet ef migrations removeBảng tra nhanh
Phần tiêu đề “Bảng tra nhanh”| Khái niệm | Ghi nhớ |
|---|---|
DbContext | Đại diện session với database |
DbSet<T> | Bảng/entity set |
| Entity | Class map tới bảng |
| Migration | Phiên bản thay đổi schema |
| Code First | Tạo database từ code |
| Connection string | Chuỗi kết nối database |
Lỗi thường gặp
Phần tiêu đề “Lỗi thường gặp”- Quên
SaveChangesAsync()nên dữ liệu không lưu. - Query bị N+1 khi load relationship.
- Đưa connection string thật lên Git.
- Dùng
Includequá nhiều làm query nặng. - Trả entity EF Core trực tiếp ra API thay vì DTO.
- Quên
AsNoTracking()cho query read-only lớn. - Sửa migration cũ đã deploy thay vì tạo migration mới.
Tham khảo chính thức
Phần tiêu đề “Tham khảo chính thức”- Overview of Entity Framework Core - Microsoft Learn
- DbContext configuration - Microsoft Learn
- Managing migrations - Microsoft Learn
- Efficient querying - Microsoft Learn
Từ khóa tìm kiếm
Phần tiêu đề “Từ khóa tìm kiếm”EF Core, Entity Framework Core, DbContext, DbSet, Entity, Migration, CRUD, Relationship, Code First, connection string, Include, AsNoTracking, tracking, projection, dotnet ef