Bỏ qua để đến nội dung

Entity Framework Core cơ bản

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.

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; }
}
Terminal window
dotnet ef migrations add InitialCreate
dotnet ef database update
Terminal window
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
// Create
db.Products.Add(new Product { Name = "Mouse", Price = 150000 });
await db.SaveChangesAsync();
// Read
List<Product> products = await db.Products.ToListAsync();
// Update
Product? product = await db.Products.FindAsync(1);
if (product is not null)
{
product.Price = 120000;
await db.SaveChangesAsync();
}
// Delete
if (product is not null)
{
db.Products.Remove(product);
await db.SaveChangesAsync();
}
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!;
}
{
"ConnectionStrings": {
"Default": "Server=.;Database=ShopDb;Trusted_Connection=True;TrustServerCertificate=True"
}
}
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
Product? product = await db.Products.FindAsync(id);
List<Product> cheapProducts = await db.Products
.Where(p => p.Price < 100000)
.OrderBy(p => p.Name)
.AsNoTracking()
.ToListAsync();
Order? order = await db.Orders
.Include(o => o.Items)
.FirstOrDefaultAsync(o => o.Id == id);
CáchKhi dùng
Tracking mặc địnhCần update/delete entity
AsNoTracking()Chỉ đọc dữ liệu, nhanh hơn
Projection SelectChỉ 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);
Terminal window
dotnet ef migrations add AddProductPrice
dotnet ef database update
dotnet ef migrations list
dotnet ef migrations remove
Khái niệmGhi nhớ
DbContextĐại diện session với database
DbSet<T>Bảng/entity set
EntityClass map tới bảng
MigrationPhiên bản thay đổi schema
Code FirstTạo database từ code
Connection stringChuỗi kết nối database
  • 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 Include quá 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.

EF Core, Entity Framework Core, DbContext, DbSet, Entity, Migration, CRUD, Relationship, Code First, connection string, Include, AsNoTracking, tracking, projection, dotnet ef