# 9.1、正向工程（Code 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 和实体类型。

## 入门指南

### 第一步

在 `Hoa.Core` 项目层中添加 `Test\Entites` 文件夹，并添加 `TestEntity.cs` 文件键入以下代码：

```csharp
using Hoa.Dependencies;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Hoa.Core.Test.Entities
{
    /// <summary>
    /// Test 表对应实体
    /// </summary>
    [Table("Test")] // 设置表名
    public class TestEntity : IEntity<int>
    {
        /// <summary>
        /// 添加Name列
        /// </summary>
        [Required]
        [MaxLength(32)]
        public string Name { get; set; }

        /// <summary>
        /// 添加CreatedTime列
        /// </summary>
        [Required]
        public DateTime CreatedTime { get; set; }
    }
}
```

### 第二步

在 `Hoa.EntityFrameworkCore` 项目层中的 `HoaDbContext.cs` 文件中添加 `TestEntity` 实体配置信息，代码如下：

```csharp
using Hoa.Core.Test.Entities;
using Microsoft.EntityFrameworkCore;

namespace Hoa.EntityFrameworkCore
{
    public class HoaDbContext : DbContext
    {
        /// <summary>
        /// 添加 Test 实体配置
        /// </summary>
        public virtual DbSet<TestEntity> Tests { get; set; }

        public HoaDbContext(DbContextOptions<HoaDbContext> options) : base(options) { }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }
}
```

### 第三步

在 `Hoa.Web.Host` 项目层中的 `appsetting.json` 中配置链接字符串，代码如下：

```javascript
{
  ...
  // 添加数据库连接字符串
  "ConnectionStrings": {
    "HoaDatabase": "Server=localhost;Database=Hoa;User=sa;Password=000000;"
  },
  ...
}
```

### 第四步

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

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

3）输入以下命令：

```bash
PM> add-migration v0.0.1_add_test_table
Build started...
Build succeeded.
To undo this action, use Remove-Migration.
PM>
```

执行完毕后会自动在 `Hoa.EntityFrameworkCore` 中创建 `Migrations` 文件夹，同时也会自动打开当前版本的表更改程序。

4）接着提交命令到数据库中

```bash
PM> update-database
Build started...
Build succeeded.
Done.
PM> 
```

之后，查看数据库管理工具（如：SQLServer），已经创建了 `Test` 表。

![](/files/-M7pBEv7rvd2BGFcdDku)

## 多DbContext情况

有时，我们的数据库操作上下文不止一个 `DbContext`，这时，需要我们指定 `-Context` 参数，参数值可以是 `DbContext` 名称，也可以是完整命名空间路径。如：

```bash
PM> Add-Migration add_test_db -Context Hoa.EntityFrameworkCore.HoaDbContext
Build started...
Build succeeded.
To undo this action, use Remove-Migration.
PM> update-database -Context Hoa.EntityFrameworkCore.HoaDbContext
Build started...
Build succeeded.
Done.
PM> 
```

更多 正向工程（Code First）方式[可以查看官方文档](https://docs.microsoft.com/zh-cn/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli)。


---

# 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/zhengxianggongcheng.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.
