資料植入Data Seeding

注意

這項功能是在 EF 核心 2.1 中新功能。This feature is new in EF Core 2.1.

資料植入可讓提供初始資料來擴展資料庫。Data seeding allows to provide initial data to populate a database. 不同於在 EF6,在 EF 核心植入的資料是做為模型設定一部分實體類型相關聯。Unlike in EF6, in EF Core, seeding data is associated with an entity type as part of the model configuration. 然後 EF 核心移轉可以自動計算項目插入、 更新或刪除作業必須升級至新版的模型資料庫時套用。Then EF Core migrations can automatically compute what insert, update or delete operations need to be applied when upgrading the database to a new version of the model.

例如,您可以使用設定的種子資料這BlogOnModelCreating:As an example, you can use this to configure seed data for a Blog in OnModelCreating:

modelBuilder.Entity<Blog>().HasData(new Blog {BlogId = 1, Url = "http://sample.com"});

若要加入實體有關聯性的外部索引鍵值必須指定。To add entities that have a relationship the foreign key values need to be specified. 外部索引鍵屬性都常陰影狀態,因此請使用能夠將設定值的匿名類別:Frequently the foreign key properties are in shadow state, so to be able to set the values an anonymous class should be used:

modelBuilder.Entity<Post>().HasData(
    new {BlogId = 1, PostId = 1, Title = "First post", Content = "Test 1"},
    new {BlogId = 1, PostId = 2, Title = "Second post", Content = "Test 2"});

一旦加入的實體,建議使用移轉套用變更。Once entities have been added, it is recommended to use migrations to apply changes.

或者,您可以使用context.Database.EnsureCreated()以建立新的資料庫包含的種子資料,例如針對測試資料庫,或使用記憶體中的提供者。Alternatively, you can use context.Database.EnsureCreated() to create a new database containing the seed data, for example for a test database or when using the in-memory provider. 請注意,如果資料庫已經存在,EnsureCreated()將兩者都不會更新結構描述或資料庫中的種子資料。Note that if the database already exists, EnsureCreated() will neither update the schema nor the seed data in the database.