πŸ“¦ Migration: CostCodeNumberChange (20250116161541)

IrbyImaging.DbContext/
└─ Migrations/
   └─ 20250116161541_CostCodeNumberChange.cs

πŸ“‘ Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Data Model: CostCode Entity
  4. Migration Class Breakdown
  5. UML Diagram
  6. Usage & Execution
  7. Error Handling & Rollback Strategy
  8. Best Practices & Considerations
  9. Conclusion

🧐 Overview & Purpose

This Entity Framework Core migration alters the CostCodeNumber column type in the irby.CostCode table:

  • Before (Down):
    • CLR type: int
    • SQL type: int
  • After (Up):
    • CLR type: string
    • SQL type: nvarchar(max)

Why?

  • Some cost codes may include leading zeros or alphanumeric patterns (e.g., "A100", "007B").
  • Switching to string avoids data loss or formatting constraints.

πŸ”§ Dependencies & Technologies

Technology/Package Version (example) Purpose
Microsoft.EntityFrameworkCore β‰₯ 7.0.0 Core ORM for migrations & data access
Microsoft.EntityFrameworkCore.SqlServer β‰₯ 7.0.0 SQL Server provider
.NET 7 (or later) 7.0+ Target framework

Note: Ensure your project references Microsoft.EntityFrameworkCore.Design if you scaffold or update migrations via CLI.


πŸ—‚οΈ Data Model: CostCode Entity

File: IrbyImaging.DbContext/Entities/CostCode.cs
(Hypothetical location – illustrates context)

public class CostCode
{
    public int Id { get; set; }

    // Changed from int to string by this migration
    public string? CostCodeNumber { get; set; }

    public string Description { get; set; } = string.Empty;
    // ... other properties ...
}
  • DbContext registration:
    public class IrbyContext : DbContext
    {
        public DbSet<CostCode> CostCodes { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<CostCode>()
                .ToTable("CostCode", schema: "irby");
        }
    }
    

πŸ”¨ Migration Class Breakdown

4.1 Class Definition

using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace IrbyImaging.DbContext.Migrations
{
    /// <inheritdoc />
    public partial class CostCodeNumberChange : Migration
    {
        // ...
    }
}
  • Namespace: IrbyImaging.DbContext.Migrations
  • Class: CostCodeNumberChange
  • Base: Migration (from EF Core)

4.2 Up Method πŸš€

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.AlterColumn<string>(
        name: "CostCodeNumber",
        schema: "irby",
        table: "CostCode",
        type: "nvarchar(max)",
        nullable: true,
        oldClrType: typeof(int),
        oldType: "int");
}

What it does

  • Alters column CostCodeNumber in schema irby.CostCode.
  • Changes from int NOT NULL β†’ nvarchar(max) NULL.
Parameter Description
name Column name ("CostCodeNumber")
schema DB schema ("irby")
table Table name ("CostCode")
type New SQL type ("nvarchar(max)")
nullable Allows NULL values (true)
oldClrType CLR type before change (typeof(int))
oldType Old SQL type ("int")

4.3 Down Method βͺ

protected override void Down(MigrationBuilder migrationBuilder)
{
    migrationBuilder.AlterColumn<int>(
        name: "CostCodeNumber",
        schema: "irby",
        table: "CostCode",
        type: "int",
        nullable: false,
        defaultValue: 0,
        oldClrType: typeof(string),
        oldType: "nvarchar(max)",
        oldNullable: true);
}

What it does

  • Reverts CostCodeNumber β†’ int NOT NULL, defaulting to 0.
Parameter Description
defaultValue Sets default for existing NULL rows to 0
oldNullable Indicates previous nullability (true)

πŸ“Š UML Diagram

classDiagram
    class Migration {
        <<interface>>
        + Up(MigrationBuilder)
        + Down(MigrationBuilder)
    }
    class CostCodeNumberChange {
        + Up(MigrationBuilder)
        + Down(MigrationBuilder)
    }
    Migration <|-- CostCodeNumberChange

πŸš€ Usage & Execution

6.1 Adding the Migration

dotnet ef migrations add CostCodeNumberChange \
  --project IrbyImaging.DbContext \
  --startup-project IrbyImaging.Api
  • --project: Points to your DbContext project
  • --startup-project: Points to the API or host project

6.2 Applying the Migration

dotnet ef database update \
  --project IrbyImaging.DbContext \
  --startup-project IrbyImaging.Api
  • Applies all pending migrations, including CostCodeNumberChange.

6.3 Reverting the Migration

  • To rollback one step:
    dotnet ef database update PreviousMigrationName
    
  • Or to revert completely:
    dotnet ef database update 0
    

⚠️ Error Handling & Rollback Strategy

  • Data truncation risk: Converting from int β†’ string is safe, but rolling back may lose alphanumeric codes.
  • Recommended:
    • Back up your database.
    • Validate existing data for non‑numeric values before applying Down.
    • Use defaultValue carefully to avoid unintended zeros.

πŸ› οΈ Best Practices & Considerations

  • Nullability: Allowing NULL provides flexibilityβ€”but ensure your application handles null or empty strings.
  • Data Validation: Consider adding a Check Constraint or Regex at the model level to enforce allowed formats.
  • Versioning: Always include a meaningful timestamp or name in the migration filename for traceability.

βœ… Conclusion

This migration is a simple yet critical schema change allowing richer cost code formats. It ensures:

  • Flexibility for alphanumeric codes
  • Minimal performance impact
  • A reversible path via the Down method

Happy migrating! πŸš€
For further queries, reach out to your team’s EF Core expert or consult the official Microsoft docs.