建立和卸除 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 服務來初始化結構描述。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();