EF Code-First - Seed Data

Seed Data trong Code-First

Bạn có thể chèn dữ liệu vào các bảng cơ sở dữ liệu của mình trong quá trình khởi tạo cơ sở dữ liệu. Điều này sẽ rất quan trọng nếu bạn muốn cung cấp một số dữ liệu thử nghiệm cho ứng dụng của bạn hoặc một số dữ liệu chính mặc định cho ứng dụng của bạn.

Để tạo dữ liệu vào cơ sở dữ liệu của bạn, bạn phải tạo một trình khởi tạo DB tùy chỉnh, như bạn đã tạo trong chương Khởi tạo cơ sở dữ liệu và ghi đè phương thức Seed.

Ví dụ sau đây cho thấy cách bạn có thể cung cấp dữ liệu mặc định cho bảng Standard trong khi khởi tạo cơ sở dữ liệu SchoolDB:

public class SchoolDBInitializer : DropCreateDatabaseAlways<SchoolDBContext>
{
    protected override void Seed(SchoolDBContext context)
    {
        IList<Standard> defaultStandards = new List<Standard>();

        defaultStandards.Add(new Standard() { StandardName = "Standard 1", Description = "First Standard" });
        defaultStandards.Add(new Standard() { StandardName = "Standard 2", Description = "Second Standard" });
        defaultStandards.Add(new Standard() { StandardName = "Standard 3", Description = "Third Standard" });

        context.Standards.AddRange(defaultStandards);

        base.Seed(context);
    }
}

Bây giờ, thiết lập lớp khởi tạo DB này trong lớp Context như bên dưới.

public class SchoolContext: DbContext 
{
    public SchoolContext(): base("SchoolDB") 
    {
        Database.SetInitializer(new SchoolDBInitializer());
    }
    
    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
}