📘 IrbyContext (Irby.DbContext.cs) Documentation

Welcome to the detailed documentation of the IrbyContext class, part of the IrbyImaging.DbContext assembly. This class is the central Entity Framework Core DbContext for all Irby Imaging data operations—managing connection strings, entity sets, and model configuration.


📑 Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Configuration & Connection Strings
  4. DbContext Registration & Usage
  5. Key Functional Areas
  6. Error Handling & Timeout Configuration
  7. Sample Code Blocks & Usage Examples
  8. UML Diagram
  9. Conclusion

🧐 Overview & Purpose

The IrbyContext class inherits from Microsoft.EntityFrameworkCore.DbContext and provides:

  • Configuration of the SQL Server database connection.
  • Registration of all domain entities via DbSet<TEntity>.
  • Entity mapping and table/column conventions in OnModelCreating.
  • Helper methods for performance tuning (e.g., command timeout).
  • Dynamic connection string selection based on environment (local, dev, QA, production).

This central context empowers the application to query, insert, update, and delete data in a type-safe, object-oriented manner.


🔗 Dependencies & Technologies

Dependency Purpose
Microsoft.EntityFrameworkCore ORM core library for data access
Microsoft.EntityFrameworkCore.Design Design-time services (e.g., migrations)
Microsoft.Extensions.Configuration Inject and read configuration (appsettings.json, etc.)
Microsoft.AspNetCore.Http IHttpContextAccessor to read current HTTP request URL
Azure.Identity (Commented code) Azure AD authentication for SQL token
IrbyImaging.DomainClasses Domain entity definitions
IrbyImaging.Utility Utility/helper classes
Syncfusion.JavaScript.DataVisualization.Models.Diagram (Imported but unused)

⚙️ Configuration & Connection Strings

IrbyContext reads multiple connection strings from IConfiguration (e.g., appsettings.json) and selects the appropriate one based on the incoming request URL:

// appsettings.json example
{
  "ConnectionStringsDev": "Server=localhost;Database=IrbyDev;Trusted_Connection=True;",
  "ConnectionStringsQA":  "Server=qa-sql;Database=IrbyQA;User Id=...;Password=...;",
  "ConnectionStringsProduction": "Server=prod-sql;Database=IrbyProd;Encrypt=True;..."
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    // Determine current URL
    var url = _httpContextAccessor.HttpContext?.Request.GetDisplayUrl() ?? "localhost";

    // Select connection string key
    var csKey = url.Contains("www.irbysystems.com") 
        ? "ConnectionStringsProduction"
        : url.Contains("irbysystemsqa.azurewebsites.net")
            ? "ConnectionStringsQA"
            : "ConnectionStringsDev";

    // Configure SQL Server
    optionsBuilder.UseSqlServer(_configuration[csKey]);
    base.OnConfiguring(optionsBuilder);
}

🔧 DbContext Registration & Usage

Register the context in Startup.cs or Program.cs:

services.AddHttpContextAccessor();  // Required for URL detection
services.AddDbContext<IrbyContext>((serviceProvider, options) => {
    var config = serviceProvider.GetRequiredService<IConfiguration>();
    var http   = serviceProvider.GetRequiredService<IHttpContextAccessor>();
    options.UseSqlServer(config.GetConnectionString("ConnectionStringsDev"));  // default dev
});

Inject and use in a service/controller:

public class AssetService
{
    private readonly IrbyContext _db;
    public AssetService(IrbyContext db) => _db = db;
    
    public async Task<List<Asset>> GetAllAssetsAsync() =>
        await _db.Assets.Include(a => a.Manufacturer).ToListAsync();
}

🚀 Key Functional Areas

1. DbSets: Entity Collections

IrbyContext exposes over 100 DbSet<TEntity> properties, grouping entities by domain. Below is a condensed table of key areas:

Domain Area Entity / DbSet
COVID Testing CovidTests
Document Imaging DocumentImages, BlobData
IPM Migrations IPMMigrations
Temporary Documents TempDocumentData
Asset Management Computers, Monitors, Assets
ODS (Legacy) ODSEmployees, ODSJobs, ODSCustomers
Procurement & Work PurchaseOrder, WorkOrder
Employees & HR Employees, Departments, Roles
Timesheets & Payroll TimeSheetEntries, PayrollMatch
Audit & Reporting AuditDetails, AuditReport
Help Desk Tickets, Issues, Updates
Irby Forms Forms
Legal Imaging DocumentTypes, DocumentAttributes, DocumentCategories
Geographic & Contracts GeoLocations, ContractsByLead
… and many more

Tip: Use LINQ and Include(...) to eagerly fetch related data.


2. OnConfiguring: Environment‑Based Connection

  • Uses IHttpContextAccessor to obtain the current request URL.
  • Chooses between Dev, QA, and Production connection strings.
  • Falls back to Dev when no HTTP context is available (e.g., CLI migrations).

3. OnModelCreating: Entity Mapping & Conventions

  1. Primary Keys & No-Key Entities

    • Explicit keys for some tables:
      modelBuilder.Entity<CovidTestData>()
          .HasKey(d => d.CovidTestDataId)
          .HasName("PK_CovidTestDataId");
      
    • Mark legacy views or reports as no-key:
      modelBuilder.Entity<LicenseReport>().HasNoKey();
      
  2. Column Type Overrides

    • Configure decimals, strings, etc.:
      modelBuilder.Entity<TimeSheetEntry>()
          .Property(p => p.HoursWorked)
          .HasColumnType("decimal(18,2)");
      
  3. Relationships & Indexes

    • Unique index on JDE numbers:
      modelBuilder.Entity<Employee>()
          .HasIndex(e => e.JdeNumber)
          .IsUnique();
      
    • Many‑to‑many mapping for Crews:
      modelBuilder.Entity<CrewEmployee>()
          .HasKey(x => new { x.CrewId, x.EmployeeId });
      
  4. Enum Conversions

    • Store enums as strings to improve readability:
      modelBuilder.Entity<Asset>()
          .Property(a => a.Status)
          .HasConversion(
             v => v.ToString(),
             v => (AssetStatus)Enum.Parse(typeof(AssetStatus), v)
          );
      

4. Helper Methods & Utilities

  • SetTimeOut(int timeout = 800)
    Adjusts the default command timeout (seconds):

    public void SetTimeOut(int timeout = 800)
    {
        this.Database.SetCommandTimeout(timeout);
    }
    
  • BlobContainerClient
    A placeholder for Azure Blob interactions (currently object typed).

  • Commented Azure AD Token Code
    Azure token-based authentication snippet:

    // var defaultCredential = new DefaultAzureCredential();
    // var token = defaultCredential.GetToken(...);
    // conn.AccessToken = token.Token;
    

⚠️ Error Handling & Timeout Configuration

  • Timeouts
    Set using SetTimeOut(...). Defaults to 800 seconds for long‑running queries.

  • Model Validation Errors
    Mis‑configured entities (e.g., missing keys) will throw exceptions at startup or migration time.

  • Connection Failures

    • Incorrect URL-driven selection may point to wrong connection string.
    • Ensure appsettings.json is populated for all environments.

💻 Sample Code Blocks & Usage Examples

1. Fetching COVID Tests

var tests = await _db.CovidTests
    .Where(t => t.TestDate >= DateTime.UtcNow.AddDays(-7))
    .ToListAsync();

2. Adding a New Asset

var asset = new Asset {
    AssetNumber = "A1001",
    Category    = AssetCategory.Computer,
    Status      = AssetStatus.Active
};
_db.Assets.Add(asset);
await _db.SaveChangesAsync();

3. Changing Timeout

_db.SetTimeOut(1200); // Increase to 20 minutes
var reports = await _db.LicenseReport.ToListAsync();

📊 UML Diagram

Below is a PlantUML snippet illustrating the core relationship between IrbyContext and a few entities:

@startuml
skinparam linetype ortho

class IrbyContext {
  +DbSet<CovidTestData> CovidTests
  +DbSet<Asset> Assets
  +DbSet<Employee> Employees
  +void SetTimeOut(int)
}

class Asset {
  +int Id
  +string AssetNumber
  +AssetStatus Status
}

class Employee {
  +int Id
  +string JdeNumber
  +EmployeeStatus Status
}

IrbyContext "1" o-- "*" Asset
IrbyContext "1" o-- "*" Employee
Asset "*" --> "1" Manufacturer : Manufacturer
Employee "*" --> "*" CrewEmployee : CrewEmployees
@enduml

Render this UML with a PlantUML viewer for a quick overview of relationships.


🏁 Conclusion

The IrbyContext is a comprehensive, environment‑aware EF Core context driving the entire Irby Imaging data layer. It unifies connection management, entity registration, and table mappings. By following this guide, you can:

  • Register the context in your ASP.NET Core pipeline.
  • Understand how entities map to database tables/views.
  • Configure performance (timeouts) and enum conversions.
  • Extend mappings or add new DbSet<> properties for future domains.

Enjoy building robust data-centric features with IrbyContext! 🎉