資料植入Data Seeding

注意

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

資料植入可讓提供初始資料來填入資料庫。Data seeding allows to provide initial data to populate a database. 不同於在 EF6,在 EF Core 植入的資料是做為模型設定一部分實體類型相關聯。Unlike in EF6, in EF Core, seeding data is associated with an entity type as part of the model configuration. 然後 EF Core移轉可以自動計算項目插入、 更新或刪除作業必須升級至新版的模型資料庫時套用。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.