2026年9月5日 星期六

筆記 DDD學習--定義好了domain & infrastructure 後,怎麼用它來create table & modify

 最近在學DDD,use case 是餐桌訂位.
辛辛苦苦地打從Domain到infra到application十八銅人陣打完了,現在要測試migration會不會成功....
以下環境是在vs2026,package Manager console; Default project設定為infrastructure 專案

指令「Add-Migration Initial -StartupProject Reservation.Api -Verbose
因為我們的db connection是放在.API專案的appsettingns.json裡,所以直接吃它的設定,
不然就是直接在AppDbContext的"CreateDbContext"裡面寫connection 設定,如下示範
------------

// Reservation.Infrastructure/Persistence/AppDbContextFactory.cs
public sealed class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    public AppDbContext CreateDbContext(string[] args)
    {
        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseSqlServer("Server=.;Database=Reservation;Trusted_Connection=True;TrustServerCertificate=True")
            .Options;
        return new AppDbContext(options);
    }
}

------------
 如果沒有錯誤的話,照理db會create出相對的table等物件
附,:如果你是用CLI(以vs code去開發的話),這裡有張參照表,
可能會用到















實驗了一張訂單後,確認動作正確,event也有發送出去
























現在重點來了,如果要加個備註欄位,要做哪些事?
首先,要先在Aggregate加上欄位(private string? Note),並在TestProject測試相關的動作正確後
接著要改的是infrastructure的  configuration  builder
---------------
            //2026/09/05,add "Note" column
            builder.Property(r => r.Note)
                 .HasColumnName("Note")
                 .HasConversion<string>()
                 .HasMaxLength(200)
                 .IsUnicode(true);   //<--多語系,沒差,因為預設就是nvarchar了
---------------
接著,請到Package manage console下指令,
Add-Migration  AddReservationNote -StartupProject Reservation.Api -Verbose
打開看一下migration指令檔(在src\Reservation.Infrastructure\Migrations最近產生的),
看看有沒有Drop Table,如果有,就請別再往下Go了--好家在你現在是在開發環境
-----
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace Reservation.Infrastructure.Migrations
{
    /// <inheritdoc />
    public partial class AddReservationNote : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<string>(
                name: "Note",
                table: "Reservations",
                type: "nvarchar(200)",
                maxLength: 200,
                nullable: true);
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "Note",
                table: "Reservations");
        }
    }
}
---
確定上述動作正確後,再回到Package Manager Console視窗,執行以下指令---
 Update-Database -StartupProject Reservation.Api
之後,你在MSSQL server managment就可以看到這個欄位加入了
現在,再新增一張訂單,便可看到新增的欄位已經可用了




























































以上
github  在此
 (現在這些東西都是給自己看的罷了,以後應該都是Agentic code generation programming了)













沒有留言:

張貼留言