using Data.SeaHavenIndustries; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace Data.SeaHavenIndustries.Migrations { /// [DbContext(typeof(ApplicationDbContext))] [Migration("20260826120000_SH221_LocationAccountScope")] public partial class SH221_LocationAccountScope : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn( name: "AccountId", table: "Locations", type: "int", nullable: true); migrationBuilder.CreateIndex( name: "IX_Locations_AccountId", table: "Locations", column: "AccountId"); migrationBuilder.AddForeignKey( name: "FK_Locations_Accounts_AccountId", table: "Locations", column: "AccountId", principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.Sql(@" ;WITH UniqueLocationAccounts AS ( SELECT wo.[LocationId] AS [LocationId], MIN(wo.[AccountId]) AS [AccountId] FROM [workOrders] wo WHERE wo.[LocationId] IS NOT NULL AND wo.[AccountId] IS NOT NULL GROUP BY wo.[LocationId] HAVING COUNT(DISTINCT wo.[AccountId]) = 1 ) UPDATE loc SET loc.[AccountId] = ula.[AccountId] FROM [Locations] loc INNER JOIN UniqueLocationAccounts ula ON ula.[LocationId] = loc.[Id] WHERE loc.[AccountId] IS NULL; "); } /// protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Locations_Accounts_AccountId", table: "Locations"); migrationBuilder.DropIndex( name: "IX_Locations_AccountId", table: "Locations"); migrationBuilder.DropColumn( name: "AccountId", table: "Locations"); } } }