Hướng Dẫn Triển Khai Lưu Trữ Dữ Liệu Với Entity Framework Core

Tổng Quan Về Entity Framework Core

EF Core đóng vai trò là một khung làm việc ORM (Object-Relational Mapping) do Microsoft phát triển. Công nghệ này giải quyết bài toán chuyển đổi giữa các đối tượng trong ngôn ngữ lập trình bậc cao và dữ liệu trong hệ quản trị cơ sở dữ liệu quan hệ. Nó cho phép nhà phát triển lưu trữ trạng thái của các đối tượng vào database một cách tự động và truy xuất dữ liệu ngược lại dưới dạng object.

Một lợi ích lớn của EF Core là khả năng tích hợp với LINQ. Nhờ đó, lập trình viên có thể thao tác truy vấn dữ liệu trên database tương tự như khi xử lý các tập hợp (collection) thông thường trong .NET.

Các Phương Thức Khởi Tạo

Việc áp dụng EF Core thường theo hai hướng tiếp cận chính:

  • Code First (Ưu tiên Code): Xây dựng lớp实体 (entity class) trước, sau đó dùng chúng để sinh ra cấu trúc bảng trong database.
  • Database First (Ưu tiên Database): Có sẵn cơ sở dữ liệu và bảng, sau đó dùng công cụ để tạo ra các lớp entity phù hợp.

Khi bắt đầu dự án mới, phương thức Code First thường được khuyến nghị hơn. Tuy nhiên, nếu cần tạo code từ database hiện có, lệnh dưới đây hữu ích:

Scaffold-DbContext

Xây Dựng Mô Hình Thực Thể

Dưới đây là ví dụ về việc định nghĩa các lớp dữ liệu bằng cách sử dụng các thuộc tính cấu hình (attributes).

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace MyCompany.Warehouse.Models
{
    public class Creator
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid IdentityKey { get; set; }

        [Required]
        [MaxLength(30)]
        public string FullName { get; set; }

        [Required]
        public DateTime DateOfBirth { get; set; }

        [Required]
        [MaxLength(50)]
        public string AddressOrigin { get; set; }

        [Required]
        [EmailAddress]
        public string ContactEmail { get; set; }

        public List<PublishedItem> Catalog { get; set; } = new List<PublishedItem>();
    }
}
namespace MyCompany.Warehouse.Models
{
    public class PublishedItem
    {
        [Key]
        public Guid UniqueId { get; set; }

        [Required]
        [MaxLength(120)]
        public string ItemName { get; set; }

        [MaxLength(600)]
        public string DetailInfo { get; set; }

        public int PageCount { get; set; }

        [ForeignKey("OwnerIdentity")]
        public Creator Owner { get; set; }

        public Guid OwnerIdentity { get; set; }
    }
}

Cấu Hình DbContext

Lớp DbContext đại diện cho phiên bản session làm việc với database. Cần khởi tạo nó với constructor nhận DbContextOptions.

using Microsoft.EntityFrameworkCore;

namespace MyCompany.Warehouse.Data
{
    public class MainContext : DbContext
    {
        public DbSet<Creator> Creators { get; set; }
        public DbSet<PublishedItem> PublishedItems { get; set; }

        public MainContext(DbContextOptions<MainContext> options) : base(options)
        {
        }
    }
}

Đăng Ký Dịch Vụ Và Kết Nối

Bước tiếp theo là thêm MainContext vào container Dependency Injection tại phần cấu hình dịch vụ.

builder.Services.AddDbContext<MainContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("ConnectionStandard"));
});

Để sử dụng UseSqlServer, cần đảm bảo đã cài đặt package tương ứng qua CLI:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Trong tệp cấu hình appsettings.json, khai báo chuỗi kết nối:

"ConnectionStrings": {
  "ConnectionStandard": "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=ProjectData;Integrated Security=True;"
}

Cài Đặt Công Cụ Và Di Chuyển (Migration)

Cần cài đặt bộ công cụ thiết kế để hỗ trợ tạo file migration:

dotnet add package Microsoft.EntityFrameworkCore.Design

Nâng cấp công cụ dotnet-ef toàn cục để tránh xung đột phiên bản:

dotnet tool update --global dotnet-ef

Thực hiện tạo file migration lần đầu:

dotnet ef migrations add CreateDatabaseSchema

Sau khi lệnh chạy thành công, thư mục Migrations sẽ chứa script SQL liên quan. Áp dụng thay đổi vào database:

dotnet ef database update

Seed Dữ Liệu Mẫu

Để đưa dữ liệu test vào database ngay khi khởi tạo, ghi đè phương thức OnModelCreating trong DbContext:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<Creator>().HasData(
        new Creator
        {
            IdentityKey = Guid.NewGuid(),
            FullName = "Sample User",
            DateOfBirth = new DateTime(1985, 5, 20),
            AddressOrigin = "Ha Noi",
            ContactEmail = "user@test.com"
        });
}

Cần tạo thêm một file migration khác để cập nhật cấu trúc seed này:

dotnet ef migrations add InsertInitialData

Sau khi migration được tạo, nội dung sẽ tự động chèn câu lệnh InsertData vào phương thức Up. Để loại bỏ dữ liệu test, hãy xóa code seed và chạy migration ngược hoặc xóa file migration gần nhất nếu chưa apply:

dotnet ef migrations remove

Đăng vào ngày 17 tháng 9 lúc 20:06