建立及卸除 APICreate and Drop APIs

EnsureCreated 和 EnsureDeleted 方法可提供 輕量替代方式來管理資料庫架構。The EnsureCreated and EnsureDeleted methods provide a lightweight alternative to Migrations for managing the database schema. 當資料是暫時性的,而且可以在架構變更時卸載時,這些方法會很有用。These methods are useful in scenarios when the data is transient and can be dropped when the schema changes. 例如,在原型設計、測試中或本機快取中。For example during prototyping, in tests, or for local caches.

有些提供者 (特別是非關聯式的提供者) 不支援遷移。Some providers (especially non-relational ones) don't support Migrations. 對於這些提供者來說,EnsureCreated 通常是初始化資料庫架構的最簡單方式。For these providers, EnsureCreated is often the easiest way to initialize the database schema.

警告

EnsureCreated 和遷移無法順利搭配運作。EnsureCreated and Migrations don't work well together. 如果您使用的是遷移,請不要使用 EnsureCreated 來初始化架構。If you're using Migrations, don't use EnsureCreated to initialize the schema.

從 EnsureCreated 轉換到遷移不是順暢的體驗。Transitioning from EnsureCreated to Migrations is not a seamless experience. 若要這麼做,最簡單的方式是卸載資料庫,並使用遷移重新建立資料庫。The simplest way to do it is to drop the database and re-create it using Migrations. 如果您預期未來會使用遷移,最好是從遷移開始,而不是使用 EnsureCreated。If you anticipate using migrations in the future, it's best to just start with Migrations instead of using EnsureCreated.

EnsureDeletedEnsureDeleted

EnsureDeleted 方法會卸載資料庫(如果存在的話)。The EnsureDeleted method will drop the database if it exists. 如果您沒有適當的許可權,則會擲回例外狀況。If you don't have the appropriate permissions, an exception is thrown.

// Drop the database if it exists
dbContext.Database.EnsureDeleted();

EnsureCreatedEnsureCreated

如果資料庫不存在,EnsureCreated 會建立資料庫,並將資料庫架構初始化。EnsureCreated will create the database if it doesn't exist and initialize the database schema. 如果有任何資料表 (包括) 其他 DbCoNtext 類別的資料表,則不會初始化架構。If any tables exist (including tables for another DbContext class), the schema won't be initialized.

// Create the database if it doesn't exist
dbContext.Database.EnsureCreated();

提示

您也可以使用這些方法的非同步版本。Async versions of these methods are also available.

SQL 指令碼SQL Script

若要取得 EnsureCreated 所使用的 SQL,您可以使用 GenerateCreateScript 方法。To get the SQL used by EnsureCreated, you can use the GenerateCreateScript method.

var sql = dbContext.Database.GenerateCreateScript();

多個 DbCoNtext 類別Multiple DbContext classes

只有當資料庫中沒有任何資料表時,EnsureCreated 才適用。EnsureCreated only works when no tables are present in the database. 如有需要,您可以撰寫自己的檢查,以查看架構是否需要初始化,並使用基礎 Irelationaldatabasecreator.hastables 服務來初始化架構。If needed, you can write your own check to see if the schema needs to be initialized, and use the underlying IRelationalDatabaseCreator service to initialize the schema.

// TODO: Check whether the schema needs to be initialized

// Initialize the schema for this DbContext
var databaseCreator = dbContext.GetService<IRelationalDatabaseCreator>();
databaseCreator.CreateTables();