创建和删除 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();