πŸ“‘ Documentation: AddDocumentIdToWorkOrder Migration (20240802135205)


πŸ“š Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Key Functional Areas
  4. Migration Class Structure
  5. Up Method – Adding DocumentId
  6. Down Method – Rolling Back Changes
  7. Applying & Rolling Back the Migration
  8. Sample SQL & EF Core Commands
  9. Integration with WorkOrder Entity
  10. Best Practices & Recommendations
  11. UML Diagram
  12. Conclusion

1. Overview & Purpose

This EF Core migration adds a new column named DocumentId to the WorkOrder table in the irby schema.

  • Context: Your application is expanding its data model to link each WorkOrder to an external or internal document reference (e.g., PDF, image, report).
  • Goal: Enable storage and retrieval of a string-based identifier for associated documents.

✨ Why?

  • Track or display a URL/ID for documents in the UI.
  • Support future features like β€œDownload Report” or β€œAttach File”.

2. Dependencies & Technologies

Technology Version / Package
.NET / C# .NET 6+, C# 10+
Entity Framework Core Microsoft.EntityFrameworkCore, Migrations API
Database SQL Server (nvarchar(max) column)
<!-- Example PackageReference in .csproj -->
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools"   Version="7.0.0" />

3. Key Functional Areas

  1. Schema Modification
    • Adds DocumentId (nullable string) to irby.WorkOrder.
  2. Up Method
    • Defines the forward migration steps.
  3. Down Method
    • Cleans up by dropping DocumentId.

4. Migration Class Structure

using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace IrbyImaging.DbContext.Migrations
{
    /// <inheritdoc />
    public partial class AddDocumentIdToWorkOrder : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            // Add column logic
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            // Remove column logic
        }
    }
}
  • Namespace: IrbyImaging.DbContext.Migrations
  • Class: AddDocumentIdToWorkOrder (inherits from Migration)
  • Methods:
    • Up() β†’ apply changes
    • Down() β†’ revert changes

5. Up Method – Adding DocumentId

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.AddColumn<string>(
        name: "DocumentId",
        schema: "irby",
        table: "WorkOrder",
        type: "nvarchar(max)",
        nullable: true);
}
  • AddColumn<string>: Generic method specifying column type.
  • Parameters:
    • name: Column name ("DocumentId").
    • schema: Database schema ("irby").
    • table: Target table ("WorkOrder").
    • type: Database-specific type ("nvarchar(max)").
    • nullable: true: Column allows NULL.

6. Down Method – Rolling Back Changes

protected override void Down(MigrationBuilder migrationBuilder)
{
    migrationBuilder.DropColumn(
        name: "DocumentId",
        schema: "irby",
        table: "WorkOrder");
}
  • DropColumn: Removes the column if you roll back this migration.
  • Ensures idempotence: Down undoes exactly what Up did.

7. Applying & Rolling Back the Migration

Apply Migration

# Using Package Manager Console (Visual Studio)
PM> Add-Migration AddDocumentIdToWorkOrder -Context IrbyDbContext
PM> Update-Database -Context IrbyDbContext
# Using .NET CLI
> dotnet ef migrations add AddDocumentIdToWorkOrder \
    --context IrbyDbContext \
    --output-dir Migrations
> dotnet ef database update --context IrbyDbContext

Rollback Migration

# Migrate back one step
PM> Update-Database <PreviousMigrationName>
# or
> dotnet ef database update <PreviousMigrationName>

8. Sample SQL & EF Core Commands

Generated SQL for Up():

ALTER TABLE [irby].[WorkOrder]
ADD [DocumentId] nvarchar(max) NULL;

Generated SQL for Down():

ALTER TABLE [irby].[WorkOrder]
DROP COLUMN [DocumentId];

9. Integration with WorkOrder Entity

Once the migration is applied, you may update your entity model:

public class WorkOrder
{
    public Guid   Id           { get; set; }
    public string Title        { get; set; }
    public string? DocumentId  { get; set; }   // ← New property

    // Navigation, other properties...
}

Usage Example

// Adding a new WorkOrder with a DocumentId
var order = new WorkOrder {
    Title = "Inspect Transformer",
    DocumentId = "DOC-2024-0001" 
};
context.WorkOrders.Add(order);
await context.SaveChangesAsync();

10. Best Practices & Recommendations

  • Nullable: By default, DocumentId is optional (nullable). If you later require it, add a defaultValue or a separate migration.
  • Data Validation: Enforce length/format in your application or via FluentValidation.
  • Indexing: If you query by DocumentId, consider adding an index in a subsequent migration.
  • Documentation: Keep migrations small, focused, and well-named.

11. UML Diagram

classDiagram
    class Migration {
      <<abstract>>
      +Up(MigrationBuilder builder)
      +Down(MigrationBuilder builder)
    }

    class AddDocumentIdToWorkOrder {
      +Up(MigrationBuilder builder)
      +Down(MigrationBuilder builder)
    }

    Migration <|-- AddDocumentIdToWorkOrder

12. Conclusion

πŸš€ AddDocumentIdToWorkOrder is a straightforward EF Core migration to extend your WorkOrder table with a new DocumentId column.

  • It encapsulates schema evolution in a controlled, reversible way.
  • Adheres to standard EF Core practices, ensuring your database stays in sync with your domain model.

Make sure to test the migration on development and staging environments before rolling it out to production. Happy coding! πŸŽ‰