Entity Framework DbMigrationsConfiguration And DbContext Seed


  1. 說明
    1. DbMigrationsConfiguration Seed
    2. DbContext Seed

筆記如何在 EntityFramework DbMigrationsConfiguration 的 Seed Method 以及 DbContext 的 Seed Method,在資料庫初始化的方式上的差別😁

logo

說明

DbMigrationsConfiguration Seed

在 Entity Framework 中,DbMigrationsConfiguration 和 DbContext 都提供了 Seed 方法來對資料庫進行初始化,但它們的使用方式和作用略有不同。

DbMigrationsConfiguration 是一個類別,用於處理 Migration 相關的設置,其中 Seed 方法用於資料庫初始化後向資料庫中加入初始資料,如系統設置、系統管理帳戶等,也可以通過 Seed 方法對資料庫結構進行修改。

在每次 Update Database Migrations 時,都會運行 Seed 方法。

DbMigrationsConfiguration 中 Seed 方法的範例:

public sealed class MyConfiguration : DbMigrationsConfiguration<MyContext>
{
    public MyConfiguration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(MyContext context)
    {
        // Add some initial data
        context.MyEntities.AddOrUpdate(x => x.Id, new MyEntity { Id = 1, Name = "Entity1" });
        context.SaveChanges();
    }
}

DbContext Seed

DbContext 中的 Seed 方法也用於初始化資料庫,但它的作用範圍更為局限。

Seed 方法通常用於初始化資料或對單一資料集(DbSet)執行某些操作,如加入、修改或刪除資料。

DbContext 中 Seed 方法的範例:

public class MyContext : DbContext
{
    public DbSet<MyEntity> MyEntities { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Entity configurations go here
    }

    protected override void Seed(MyContext context)
    {
        // Add some initial data
        context.MyEntities.Add(new MyEntity { Name = "Entity1" });
        context.SaveChanges();
    }
}

兩者的相同之處在於為資料庫進行初始化,加入初始資料,修改資料庫結構等。

而 DbMigrationsConfiguration 的 Seed 方法用於在每次的 Update Database Migration,而 DbContext 的 Seed 方法用於 DbContext 產生 Instance 物件化時。

DbMigrationsConfiguration 的 Seed 方法範圍更廣,可以操作整個資料庫結構,而 DbContext 的 Seed 方法則較為局限,只能操作單一資料集 (DbSet)。

根據具體需求和使用場景,可以選擇使用其中之一或兩者結合使用。