管理数据库架构Managing Database Schemas

EF Core 提供两种主要方法来保持 EF Core 模型和数据库架构同步。至于我们应该选用哪个方法,请确定你是希望以 EF Core 模型为准还是以数据库为准。EF Core provides two primary ways of keeping your EF Core model and database schema in sync. To choose between the two, decide whether your EF Core model or the database schema is the source of truth.

如果希望以 EF Core 模型为准,请使用迁移If you want your EF Core model to be the source of truth, use Migrations. 对 EF Core 模型进行更改时,此方法会以增量方式将相应架构更改应用到数据库,以使数据库保持与 EF Core 模型兼容。As you make changes to your EF Core model, this approach incrementally applies the corresponding schema changes to your database so that it remains compatible with your EF Core model.

如果希望以数据库架构为准,请使用反向工程Use Reverse Engineering if you want your database schema to be the source of truth. 使用此方法,可通过将数据库架构反向工程到 EF Core 模型来生成相应的 DbContext 和实体类型。This approach allows you to scaffold a DbContext and the entity type classes by reverse engineering your database schema into an EF Core model.

备注

创建和删除 API 也可从 EF Core 模型创建数据库架构。The create and drop APIs can also create the database schema from your EF Core model. 但是,它们主要适用于允许删除数据库的场景,比如测试、原型制作等。However, they are primarily for testing, prototyping, and other scenarios where dropping the database is acceptable.