shoc-backend/Data.SeaHavenIndustries/Migrations/20260806123838_SH221_WorkOrderAccountScope.cs

111 lines
3.3 KiB
C#
Raw Normal View History

using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Data.SeaHavenIndustries.Migrations
{
/// <inheritdoc />
public partial class SH221_WorkOrderAccountScope : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "AccountId",
table: "workOrders",
type: "int",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "AccountId",
table: "AspNetUsers",
type: "int",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_workOrders_AccountId",
table: "workOrders",
column: "AccountId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUsers_AccountId",
table: "AspNetUsers",
column: "AccountId");
migrationBuilder.AddForeignKey(
name: "FK_AspNetUsers_Accounts_AccountId",
table: "AspNetUsers",
column: "AccountId",
principalTable: "Accounts",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_workOrders_Accounts_AccountId",
table: "workOrders",
column: "AccountId",
principalTable: "Accounts",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
// Best-effort backfill: unique Accounts.Name match against WorkOrder.Customer.
migrationBuilder.Sql(@"
;WITH UniqueAccounts AS (
SELECT
a.[Id],
a.[Name]
FROM [Accounts] a
WHERE a.[Name] IS NOT NULL
AND LTRIM(RTRIM(a.[Name])) <> ''
AND (a.[IsDeleted] IS NULL OR a.[IsDeleted] = 0)
AND a.[Name] IN (
SELECT a2.[Name]
FROM [Accounts] a2
WHERE a2.[Name] IS NOT NULL
AND LTRIM(RTRIM(a2.[Name])) <> ''
AND (a2.[IsDeleted] IS NULL OR a2.[IsDeleted] = 0)
GROUP BY a2.[Name]
HAVING COUNT(*) = 1
)
)
UPDATE wo
SET wo.[AccountId] = ua.[Id]
FROM [workOrders] wo
INNER JOIN UniqueAccounts ua
ON ua.[Name] = wo.[Customer]
WHERE wo.[AccountId] IS NULL
AND wo.[Customer] IS NOT NULL
AND LTRIM(RTRIM(wo.[Customer])) <> '';
");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_AspNetUsers_Accounts_AccountId",
table: "AspNetUsers");
migrationBuilder.DropForeignKey(
name: "FK_workOrders_Accounts_AccountId",
table: "workOrders");
migrationBuilder.DropIndex(
name: "IX_workOrders_AccountId",
table: "workOrders");
migrationBuilder.DropIndex(
name: "IX_AspNetUsers_AccountId",
table: "AspNetUsers");
migrationBuilder.DropColumn(
name: "AccountId",
table: "workOrders");
migrationBuilder.DropColumn(
name: "AccountId",
table: "AspNetUsers");
}
}
}