🗂 Documentation: 20230626202026_AddNewTableBlobData.cs Migration

File Path:
IrbyImaging.DbContext/Migrations/20230626202026_AddNewTableBlobData.cs


📑 Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Migration Structure & Key Functional Areas
  4. Data Models & Schema Changes
    4.1. BlobData Table
    4.2. TempDocumentData Table Update
  5. Up() Method Explained
  6. Down() Method Explained
  7. Applying the Migration
  8. UML Diagram 📊
  9. Sample Code Blocks & Usage Examples
  10. Conclusion 🎯

1. Overview & Purpose

This Entity Framework Core migration introduces a brand-new table called BlobData and links it (via a nullable GUID) to the existing TempDocumentData table. The goal is to store large binary objects (blobs, e.g., image files) separately, improving the modularity of document‑related data.

  • Why?
    • Centralize binary content in a dedicated table
    • Reduce payload size on frequently accessed TempDocumentData records
    • Enable more efficient backup/restore and table‐partition strategies

2. Dependencies & Technologies

Technology Version Notes
.NET / .NET Core 6.0+ C# 10+, nullable reference types enabled
Microsoft.EntityFrameworkCore 6.0+ MigrationBuilder, Migration base classes
SQL Server (T-SQL) 2012+ uniqueidentifier, varbinary(max)

3. Migration Structure & Key Functional Areas

public partial class AddNewTableBlobData : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder) { /* … */ }
    protected override void Down(MigrationBuilder migrationBuilder) { /* … */ }
}
  • Class

    • Inherits from Microsoft.EntityFrameworkCore.Migrations.Migration
    • Named by EF Core as 20230626202026_AddNewTableBlobData to reflect timestamp + purpose
  • Key Methods

    1. Up(): Defines schema changes to apply
    2. Down(): Reverts those changes (rollback)

4. Data Models & Schema Changes

4.1. BlobData Table

Column Name Data Type Nullable Key Description
BlobDataId uniqueidentifier NO PK Surrogate primary key
ImageContents varbinary(max) YES — Raw binary data of the blob/image
TempDocumentDataId uniqueidentifier YES — Optional FK reference container
  • Schema: irby
  • Table: BlobData
  • Primary Key: PK_BlobData (BlobDataId)

4.2. TempDocumentData Table Update

Operation Schema Table Column Type Nullable Description
Add irby TempDocumentData BlobDataId uniqueidentifier YES FK placeholder for BlobData

Note:

  • The migration adds a column but does not create an explicit FK constraint.
  • You may want to add a foreign key in a subsequent migration or configure it via Fluent API.

5. Up() Method Explained

protected override void Up(MigrationBuilder migrationBuilder)
{
    // 1️⃣ Add a nullable GUID column to TempDocumentData
    migrationBuilder.AddColumn<Guid>(
        name: "BlobDataId",
        schema: "irby",
        table: "TempDocumentData",
        type: "uniqueidentifier",
        nullable: true);

    // 2️⃣ Create the new BlobData table
    migrationBuilder.CreateTable(
        name: "BlobData",
        schema: "irby",
        columns: table => new
        {
            BlobDataId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
            ImageContents = table.Column<byte[]>(type: "varbinary(max)", nullable: true),
            TempDocumentDataId = table.Column<Guid>(type: "uniqueidentifier", nullable: true)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_BlobData", x => x.BlobDataId);
        });
}
  • Step-by-step
    1. AddColumn<Guid>
      • Adds BlobDataId to TempDocumentData
      • Makes relationship optional
    2. CreateTable("BlobData")
      • Defines columns + PK
      • Does not define Foreign Key constraints

6. Down() Method Explained

protected override void Down(MigrationBuilder migrationBuilder)
{
    // 1️⃣ Drop the BlobData table
    migrationBuilder.DropTable(
        name: "BlobData",
        schema: "irby");

    // 2️⃣ Remove the BlobDataId column from TempDocumentData
    migrationBuilder.DropColumn(
        name: "BlobDataId",
        schema: "irby",
        table: "TempDocumentData");
}
  • Rollback order matters!
    • DropTable first avoids dependency issues (if FK existed).
    • DropColumn cleans up the placeholder on TempDocumentData.

7. Applying the Migration

  1. Add & Scaffold (already done in this file)
    dotnet ef migrations add AddNewTableBlobData
    
  2. Update Database
    dotnet ef database update
    
  3. Verify
    • Check your database:
      • irby.TempDocumentData now has BlobDataId
      • New table: irby.BlobData

8. UML Diagram 📊

@startuml
skinparam classAttributeIconSize 0

class TempDocumentData {
  + Guid TempDocumentDataId
  + Guid? BlobDataId
  // …other properties…
}

class BlobData {
  + Guid BlobDataId
  + byte[] ImageContents
  + Guid? TempDocumentDataId
}

TempDocumentData "1" -- "0..1" BlobData : references >
@enduml

Note: Relationship is logical. EF Fluent API or Data Annotations can materialize the FK.


9. Sample Code Blocks & Usage Examples

9.1. Model Definitions

// BlobData.cs
public class BlobData
{
    public Guid BlobDataId { get; set; }
    public byte[]? ImageContents { get; set; }
    public Guid? TempDocumentDataId { get; set; }
    public TempDocumentData? TempDocumentData { get; set; }
}

// TempDocumentData.cs (partial)
public class TempDocumentData
{
    public Guid TempDocumentDataId { get; set; }
    public Guid? BlobDataId { get; set; }
    public BlobData? BlobData { get; set; }
    // …other properties…
}

9.2. DbContext Configuration

public class IrbyContext : DbContext
{
    public DbSet<BlobData> BlobData { get; set; }
    public DbSet<TempDocumentData> TempDocumentData { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("irby");

        modelBuilder.Entity<BlobData>()
            .HasKey(b => b.BlobDataId);

        modelBuilder.Entity<TempDocumentData>()
            .HasOne(td => td.BlobData)
            .WithOne(b => b.TempDocumentData)
            .HasForeignKey<TempDocumentData>(td => td.BlobDataId);
    }
}

9.3. CRUD Example

// 1️⃣ Create and attach BlobData to a TempDocumentData record
var doc = await context.TempDocumentData.FindAsync(existingId);
doc.BlobData = new BlobData
{
    ImageContents = await File.ReadAllBytesAsync("scan.png")
};
await context.SaveChangesAsync();

// 2️⃣ Query joined data
var result = await context.TempDocumentData
    .Include(td => td.BlobData)
    .FirstOrDefaultAsync(td => td.TempDocumentDataId == existingId);

10. Conclusion 🎯

  • What we did:
    • Added a new table irby.BlobData to store binary blobs.
    • Extended irby.TempDocumentData with a nullable BlobDataId.
  • Why this matters:
    • Decouples large binary storage from document metadata.
    • Improves performance, maintainability, and data organization.
  • Next steps:
    • Add FK constraints & cascading rules if desired.
    • Create additional queries or repositories for BlobData.
    • Implement cleanup routines for orphaned blobs (if any).

🚀 Migration implemented successfully! You can now store and manage binary data within your IrbyImaging solution.