📦 IrbyContextModelSnapshot.cs Documentation

Welcome to the detailed documentation for the IrbyContextModelSnapshot.cs file, an EF Core Model Snapshot in the IrbyImaging.DbContext.Migrations namespace. This file is auto‑generated and represents the current shape of your database model. It is used by EF Core to compare the code model with the database schema when adding or applying migrations.


📑 Table of Contents

  1. Overview & Purpose
  2. Key Concepts
  3. The BuildModel Method
  4. Entity Configuration Examples
  5. Relationships & Navigation Properties
  6. Table‑Per‑Hierarchy (TPH) Inheritance Example
  7. Using EF Core Migrations
  8. Sample Usage & Code Snippets
  9. Generating UML Diagrams
  10. Conclusion

1. Overview & Purpose

🚀 What is a Model Snapshot?
A Model Snapshot is an EF Core artifact that captures the current state of your EF Core model. When you add a new migration, EF compares the snapshot with your updated model classes to calculate the changes.

Key Points:

  • Auto-generated by the dotnet ef migrations add command.
  • Found under Migrations/IrbyContextModelSnapshot.cs.
  • Do not manually edit this file; EF will overwrite it.
  • Ensures accurate diff comparisons between code and database.

2. Key Concepts

Concept Description
ModelSnapshot Base class that holds the model metadata.
BuildModel(ModelBuilder) Method that re‑creates the EF model in code.
EntityTypeBuilder Fluent API used to configure tables, keys, indexes, relationships, etc.
Annotations Metadata such as product version, table schema, max identifier length.
TPH Inheritance All derived asset types stored in a single Asset table with a discriminator column.

3. The BuildModel Method

The heart of the snapshot is the BuildModel override:

[DbContext(typeof(IrbyContext))]
partial class IrbyContextModelSnapshot : ModelSnapshot
{
    protected override void BuildModel(ModelBuilder modelBuilder)
    {
        #pragma warning disable 612, 618
        modelBuilder
            .HasAnnotation("ProductVersion", "9.0.0")
            .HasAnnotation("Relational:MaxIdentifierLength", 128);

        // Use SQL Server identity columns by default
        SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);

        // ----- Entity configurations follow -----
        modelBuilder.Entity("IrbyImaging.DomainClasses.AccountBalances", b => { … });
        modelBuilder.Entity("IrbyImaging.DomainClasses.Asset", b => { … });
        // … hundreds more …
        #pragma warning restore 612, 618
    }
}
  • Annotations: Specify the EF Core runtime version and SQL Server conventions.
  • Entity Definitions: Each call to modelBuilder.Entity(…) re‑creates one table mapping.

4. Entity Configuration Examples

Below are representative examples illustrating how entities are configured:

AccountBalances

Property Column Type Notes
AccountBalanceId uniqueidentifier Primary Key, generated on add
Customer nvarchar(max)
Cost decimal(18,2)
Table irby.AccountBalances Schema irby
modelBuilder.Entity("IrbyImaging.DomainClasses.AccountBalances", b =>
{
    b.Property<Guid>("AccountBalanceId")
        .ValueGeneratedOnAdd()
        .HasColumnType("uniqueidentifier");

    b.Property<string>("Customer")
        .HasColumnType("nvarchar(max)");

    b.Property<decimal>("Cost")
        .HasColumnType("decimal(18,2)");

    b.HasKey("AccountBalanceId");
    b.ToTable("AccountBalances", "irby");
});

Asset & TPH Inheritance

The Asset entity uses Table‑Per‑Hierarchy (TPH) inheritance. A single SQL table called irby.Asset stores all derived types (e.g., Computer, MobileDevice), differentiated by the Discriminator column.

modelBuilder.Entity("IrbyImaging.DomainClasses.Asset", b =>
{
    b.Property<Guid>("Id")
     .ValueGeneratedOnAdd()
     .HasColumnType("uniqueidentifier");

    b.Property<string>("Category")
     .IsRequired()
     .HasColumnType("nvarchar(max)");

    b.Property<string>("Discriminator")
     .IsRequired()
     .HasMaxLength(21)
     .HasColumnType("nvarchar(21)");

    // Common props:
    b.Property<string>("SerialNumber").HasColumnType("nvarchar(max)");
    b.Property<DateTimeOffset>("PurchaseDate").HasColumnType("datetimeoffset");
    // …

    b.HasKey("Id");
    b.HasIndex("FieldOfficeId");
    b.HasIndex("ModelId");
    b.HasIndex("OwnerId");

    b.ToTable("Asset", "irby");
    b.HasDiscriminator().HasValue("Asset");
    b.UseTphMappingStrategy();
});

// Derived example:
modelBuilder.Entity("IrbyImaging.DomainClasses.Computer", b =>
{
    b.HasBaseType("IrbyImaging.DomainClasses.Asset");
    b.Property<string>("AssetNumber")
        .HasColumnType("nvarchar(max)")
        .HasColumnName("AssetNumber");
    b.Property<int>("OperatingSystemId")
        .HasColumnType("int")
        .HasColumnName("OperatingSystemId");
    b.HasIndex("OperatingSystemId");
    b.ToTable("Asset", "irby");
    b.HasDiscriminator().HasValue("Computer");
});

5. Relationships & Navigation Properties

EF Core configures foreign keys and navigation properties in code:

// Asset → AssetModel (many‑to‑one)
modelBuilder.Entity("IrbyImaging.DomainClasses.Asset", b =>
{
    b.HasOne("IrbyImaging.DomainClasses.AssetModel", "Model")
     .WithMany()
     .HasForeignKey("ModelId")
     .OnDelete(DeleteBehavior.Cascade)
     .IsRequired();
    // Navigation configured:
    b.Navigation("Model");
});

// Job → FieldOffice (many‑to‑one)
modelBuilder.Entity("IrbyImaging.DomainClasses.Job", b =>
{
    b.HasOne("IrbyImaging.DomainClasses.FieldOffice", null)
     .WithMany("Jobs")
     .HasForeignKey("FieldOfficeId");
    b.Navigation("Jobs");
});
  • HasOne/WithMany: Defines cardinality.
  • HasForeignKey: Links the FK column.
  • OnDelete: Cascade behaviours.
  • Navigation: EF tracks collection and reference navigations.

6. Table-per-Hierarchy (TPH) Inheritance Example

Below is a Mermaid UML snippet illustrating the TPH inheritance for Asset:

classDiagram
    class Asset {
      +Guid Id
      +string Category
      +string Discriminator
      +string SerialNumber
      +DateTimeOffset PurchaseDate
      +Guid? FieldOfficeId
      +int ModelId
      +Guid? OwnerId
    }
    class Computer {
      +string AssetNumber
      +int OperatingSystemId
    }
    class MobileDevice {
      +string Carrier
      +string Imei
      +string PhoneNumber
    }
    Asset <|-- Computer
    Asset <|-- MobileDevice

7. Using EF Core Migrations

Common Commands

# Add a new migration after changing your model classes
dotnet ef migrations add AddNewPropertyToAccountBalances

# Apply pending migrations to the database
dotnet ef database update

# Generate SQL script
dotnet ef migrations script -o migration.sql

Note: Running a migration will update the ModelSnapshot automatically.


8. Sample Usage & Code Snippets

1. DbContext Registration

services.AddDbContext<IrbyContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("IrbyDb")));

2. Querying Entities

using var scope = serviceProvider.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<IrbyContext>();

// List all active assets
var activeAssets = context.Assets
    .Where(a => a.Status == "Active")
    .Include(a => a.Owner)
    .ToList();

3. Adding a New Entity

var ledger = new AccountLedger
{
    BatchNumber = "B123",
    Amount = 150.00M,
    GLDate = DateTime.UtcNow,
    ReportingMonth = 9,
    ReportingYear = 2024
};
context.AccountLedger.Add(ledger);
context.SaveChanges();

9. Generating UML Diagrams

To visually inspect the model, consider using the EF Core Power Tools extension:

  1. Install EF Core Power Tools in Visual Studio.
  2. Right‑click your project → EF Core Power Tools → Reverse Engineer.
  3. Generate DGML or PlantUML diagrams of your DbContext.

10. Conclusion

🛠 IrbyContextModelSnapshot.cs is a vital EF Core artifact that:

  • Captures the complete mapping of 180+ tables (entities) to the SQL schema.
  • Enables EF Core to identify model changes and scaffold new migrations.
  • Should be left untouched and is automatically updated on each migration.

Keep your domain classes up to date, and let EF Core handle the snapshot. Happy coding! 😄🚀


Generated by AI Assistant – tailored for IrbyImaging’s EF Core model.