# 9.2、逆向工程（Database First）

## 关于正向工程和逆向工程

EF Core 提供两种主要方法来保持 EF Core 模型和数据库架构同步。至于我们应该选用哪个方法，请确定你是希望以 EF Core 模型为准还是以数据库为准。&#x20;

如果希望以 EF Core 模型为准，请使用[正向工程（Code First）](https://monksoul.gitbook.io/hoa/shujukucaozuoshinan/zhengxianggongcheng)。 对 EF Core 模型进行更改时，此方法会以增量方式将相应架构更改应用到数据库，以使数据库保持与 EF Core 模型兼容。

&#x20;如果希望以数据库架构为准，请使用[逆向工程（Database First）](https://monksoul.gitbook.io/hoa/shujukucaozuoshinan/nixianggongcheng)。 使用此方法，可通过将数据库架构反向工程到 EF Core 模型来生成相应的 DbContext 和实体类型。

## 入门指南

### 第一步

在数据库管理工具中（如：SQLServer）中创建 `Hoa` 数据库，并执行以下 Sql 语句：

```sql
CREATE TABLE Test(
    [Id] INT NOT NULL PRIMARY KEY,
    [Name] NVARCHAR(32) NOT NULL,
    [CreatedTime] DATETIME NOT NULL
)
```

### 第二步

1） 在 `Visual Studio 2019` 中打开 `程序包管理控制台` (工具 -> Nuget 包管理器 -> 程序包管理控制台)

2） 在 `程序包管理控制台` 中，切换 **默认项目** 为 `Hoa.Core`

3）输入以下命令：

```bash
PM> & "Hoa.EntityFrameworkCore\db_to_entities.ps1"
```

4）选择数据库连接字符串

![](/files/-MCM02cJwB3VHLExncR-)

5）选择你要生成的表或视图（支持多选）

![](/files/-MCM08xOaZUDBXzBYu7P)

6）选择保存的目录

![](/files/-MCM0FpdCLhuTsqy_2HB)

7）开始生成

```
Hoa Db First 生成器 v2.0.0 
==============================
正在检查默认项目设置......
默认项目设置正确
开始将数据库表生成对应的模型......
正在备份原来的HoaDbContext.cs
备份成功
==============================
当前备份文件路径为：./Hoa.EntityFrameworkCore/DbContextBakFiles/HoaDbContext.cs.20200520183915
注意！！！请将该备件文件内容和现有的 HoaDbContext 内容进行合并
==============================
==============================
生成模型的表有: Test
==============================
模型类文件保存路径为: Hoa.Core/Test/Entities/
==============================
Build started...
Build succeeded.
Unable to find a table in the database matching the selected table Test.
开始替换默认命名空间......
开始删除无用代码......
生成成功
PM> 
```

8）命令执行完成后，点击确定

![](/files/-MCR65GSB6oDe_gDDICG)

9）**删除 `Hoa.Core` 层的 `HoaDbContext` 链接文件！**

![](/files/-MCR6ghOpstoBbP61ju8)

## 逆向工程脚本

### 基础命令

```bash
& "Hoa.EntityFrameworkCore\db_to_entities.ps1"
```

### 参数配置说明

* `-Schemas`: 字符串数组类型, 数据库 `Schema`, 选填, 多个表用英文逗号隔开,**注意：如果指定了这个参数，就会覆盖-Table参数，生成这个Schemas中所有的表**，所以通常我们不需要指定！！！！
* `-Context`：在**多数据库上下文**时，需要指定完整的 `DbConext` 路径，也就是包含命名空间。默认是：`Hoa.EntityFrameworkCore.HoaDbContext`

更多逆向工程[可查看官方文档](https://docs.microsoft.com/zh-cn/ef/core/managing-schemas/scaffolding)。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://monksoul.gitbook.io/hoa/shujukucaozuoshinan/nixianggongcheng.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
