🎉 EF Core Migration Documentation
IrbyImaging.DbContext/Migrations/20240201193852_UpdateEmployeeTableWithNewColumns5.Designer.cs
📑 Table of Contents
- Overview & Purpose
- Migration Designer File Structure
- BuildTargetModel Method
- Key Entity Configurations
- Relationships & Navigation Properties
- Identity Columns & Discriminator Strategy
- Using EF Core Migrations (CLI & Code)
- UML Diagram: Employee & Related Entities
- Sample Usage & Code Snippets
- Conclusion
🧐 1. Overview & Purpose
This auto-generated designer file describes the target model for the EF Core migration UpdateEmployeeTableWithNewColumns5.
- It is paired with
20240201193852_UpdateEmployeeTableWithNewColumns5.cs(which contains theUp()andDown()methods). - The designer shows how all domain entities—including Employee, Asset, Job, Role, etc.—are mapped to tables, columns, keys, indexes, and relationships.
- Purpose: Ensure the database schema matches your EF Core model after applying the migration.
🏗️ 2. Migration Designer File Structure
namespace IrbyImaging.DbContext.Migrations
{
[DbContext(typeof(IrbyContext))]
[Migration("20240201193852_UpdateEmployeeTableWithNewColumns5")]
partial class UpdateEmployeeTableWithNewColumns5
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
// 1. Global annotations
modelBuilder
.HasAnnotation("ProductVersion", "7.0.7")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
// 2. Entity configurations...
modelBuilder.Entity("IrbyImaging.DomainClasses.Asset", b => { ... });
modelBuilder.Entity("IrbyImaging.DomainClasses.Employee", b => { ... });
// ... all other entities
// 3. Relationship configurations
modelBuilder.Entity("IrbyImaging.DomainClasses.Asset", b => { b.HasOne(...); });
// ...
}
}
}
Key Sections:
- Global Annotations: Versioning, identifier length, identity columns.
- Entity Definitions: One block per domain class.
- Relationship Setup: Foreign keys and navigation mapping.
🔨 3. BuildTargetModel Method
-
Signature:
protected override void BuildTargetModel(ModelBuilder modelBuilder) -
Function: Defines how the EF Core model should look after this migration is applied.
-
ModelBuilder: Fluent API to configure entities:
modelBuilder.Entity<TEntity>(entity => { entity.Property(p => p.Id) .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); entity.HasKey(p => p.Id); entity.HasIndex(p => p.ForeignKey); entity.ToTable("TableName", "schema"); // Discriminator, TPH etc. entity.HasDiscriminator<string>("Discriminator") .HasValue("Asset"); });
🔑 4. Key Entity Configurations
4.1 Asset (TPH Inheritance) 🖥️🚗📱
| Aspect | Configuration |
|---|---|
| Table & Schema | Asset table in schema irby |
| Primary Key | Id (GUID, Identity) |
| Discriminator | Column "Discriminator" for TPH mapping |
| Inheritance Strategy | UseTphMappingStrategy() |
| Child Types | Computer, MobileDevice, SafetyEquipment, DeskPhone, … |
modelBuilder.Entity("IrbyImaging.DomainClasses.Asset", b =>
{
b.Property<Guid>("Id").ValueGeneratedOnAdd().HasColumnType("uniqueidentifier");
b.Property<string>("Category").IsRequired().HasColumnType("nvarchar(max)");
// ...
b.HasKey("Id");
b.HasIndex("OwnerId");
b.ToTable("Asset","irby");
b.HasDiscriminator<string>("Discriminator").HasValue("Asset");
b.UseTphMappingStrategy();
});
4.2 Employee (Updated Table) 👷♂️
This migration updates the Employee entity with new columns.
| Property | Type | Nullable | Constraints |
|---|---|---|---|
| EmployeeId | GUID | No | PK, ValueGeneratedOnAdd |
| AzureUserId | GUID | No | |
| Birthday | DateTime? | Yes | |
| BusinessUnit | nvarchar(max) | Yes | |
| City | nvarchar(max) | Yes | |
| DepartmentId | GUID? | Yes | FK → Department |
| DisplayName | nvarchar(max) | Yes | |
| nvarchar(max) | Yes | ||
| EmploymentStartDate | DateTime? | Yes | |
| FirstName | nvarchar(max) | Yes | |
| JdeNumber | nvarchar(450) | Yes | Unique Index |
| JobId | GUID | No | FK → Job (cascade on delete) |
| LastFourSSN | nvarchar(max) | Yes | |
| LastName | nvarchar(max) | Yes | |
| ManagerId | GUID? | Yes | FK → Employee (self‐ref) |
| ManagerName | nvarchar(max) | Yes | |
| RoleId | GUID? | Yes | FK → Role |
| Status | nvarchar(max) | No | Required |
| … (plus other address, pay, etc.) |
modelBuilder.Entity("IrbyImaging.DomainClasses.Employee", b =>
{
b.Property<Guid>("EmployeeId")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("JdeNumber")
.HasColumnType("nvarchar(450)");
b.HasIndex("JdeNumber")
.IsUnique()
.HasFilter("[JdeNumber] IS NOT NULL");
b.HasKey("EmployeeId");
b.ToTable("Employee","irby");
});
4.3 Other Domain Entities (Summary) 📦
Given the breadth of your domain, the designer configures 60+ entities including:
- Assets & AssetHistory
- Jobs, FieldOffice, Customer
- Tickets, Updates, TimeSheetEntry, TimeEntryType
- DocumentImage, DocumentAttribute, DocumentCategory
- AuditDetail, AuditReport
- GeneralLedger, GLTypeDetail, BillingInvoice
- ODSEmployee, ODSJob, ODSCustomer
- …and many reporting views/tables
🔗 5. Relationships & Navigation Properties
Every foreign key is declared with .HasOne(...).WithMany(...).HasForeignKey(...).
Example: Employee → Department
modelBuilder.Entity("IrbyImaging.DomainClasses.Employee", b =>
{
b.HasOne("IrbyImaging.DomainClasses.Department","Department")
.WithMany()
.HasForeignKey("DepartmentId");
b.Navigation("Department");
});
Self‑reference for manager:
b.HasOne("IrbyImaging.DomainClasses.Employee","Manager")
.WithMany()
.HasForeignKey("ManagerId");
🔒 6. Identity Columns & Discriminator Strategy
-
Identity Columns:
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);Enables
IDENTITY-style columns in SQL Server for all integer keys. -
Table‑Per‑Hierarchy (TPH):
.HasDiscriminator<string>("Discriminator") .UseTphMappingStrategy();Maps a class‐inheritance hierarchy into a single table with a
Discriminatorcolumn.
🛠️ 7. Using EF Core Migrations (CLI & Code)
Generating a New Migration
dotnet ef migrations add UpdateEmployeeTableWithNewColumns5 \
--context IrbyContext \
--project IrbyImaging.DbContext
Applying to Database
dotnet ef database update \
--context IrbyContext \
--project IrbyImaging.DbContext
Rollback
dotnet ef database update LastGoodMigrationName
📊 8. UML Diagram: Employee & Related Entities
@startuml
entity Employee {
*EmployeeId : GUID
--
FirstName : string
LastName : string
JdeNumber : string
Status : string
}
entity Department {
*DepartmentId : GUID
Name : string
}
entity Job {
*JobId : GUID
Name : string
JdeNumber : string
}
entity Role {
*RoleId : GUID
Name : string
}
Department ||--o{ Employee : has
Job ||--o{ Employee : employs
Role ||--o{ Employee : authorizes
Employee }o--o{ Employee : manages (ManagerId)
@enduml
Note: Copy the above PlantUML into an online renderer to view the diagram.
💻 9. Sample Usage & Code Snippets
Querying Updated Employee Data
using var context = new IrbyContext();
var activeEmployees = context.Employees
.Where(e => e.Status == "Active")
.Select(e => new
{
e.DisplayName,
e.Email,
e.Job.Name,
e.Department.Name
})
.ToList();
Inserting a New Employee
var newEmp = new Employee
{
FirstName = "Alice",
LastName = "Johnson",
JdeNumber = "123456",
Status = "Active",
JobId = someJobId,
DepartmentId = someDeptId,
AzureUserId = Guid.NewGuid()
};
context.Employees.Add(newEmp);
context.SaveChanges();
🎯 10. Conclusion
This designer file is the backbone of your EF Core migration, reflecting the entire model after UpdateEmployeeTableWithNewColumns5 is applied.
- It ensures consistency between your C# domain classes and the SQL schema.
- By understanding the ModelBuilder API, you can customize conventions, table names, indexes, and relationships.
Happy coding! 🚀