建立及卸除 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();