A senior code review of an EF Core model configuration covering a hard-coded connection string in OnConfiguring, lazy loading proxies, nvarchar(max) strings, cascade delete everywhere and random GUID clustered keys, ranked by severity with a rewrite.
I rank findings by severity:
OnConfiguring: a secret in source control and configuration that can't change per environment. Move it to configuration (user secrets locally, Key Vault or Entra ID managed identity in Azure) and register with AddDbContext.Restrict for business data.Include or projection.Guid.NewGuid() clustered keys: page splits and fragmentation; let EF Core generate sequential GUIDs or make the PK nonclustered.nvarchar(max), which can't be an index key.Then I fix it systemically with ConfigureConventions defaults and a migration checklist. The trade-off: defaults are fast to write, but each one here costs security, data or performance later.
"I'd review this in severity order, because a model configuration is the schema the service will live with for years. First, the connection string in
OnConfiguring. If it contains a password it's a leaked secret the moment it's committed, and even without one it can't vary by environment and bypasses DI. I'd ask forAddDbContextinProgram.csreading from configuration, and in Azure,Authentication=Active Directory Defaultwith a managed identity so there's no password at all. That's a blocking comment, and the secret needs rotating if it's real.Second, cascade delete on every relationship. That's a data-loss risk: deleting a customer would remove orders and invoices, and with an audit trail and the Privacy Act's retention expectations we usually don't want hard deletes at all. SQL Server will also reject it once two cascade paths reach one table. Third, lazy loading proxies. In an API they turn every navigation access into a query, so serialising a list of 50 orders can fire 50 more queries, and the serializer walks back-references into cycles. I'd remove
UseLazyLoadingProxiesand load explicitly. For example, at [company] removing lazy loading from one endpoint took it from [120] queries per request to [2] and p95 from [900 ms] to [80 ms].Then the physical design:
Guid.NewGuid()as a clustered key fragments the index on every insert, so I'd let EF Core's sequential generator assign it or make the PK nonclustered; and unconfigured strings arenvarchar(max), which can't be index keys. The mistake I'd avoid as a reviewer is leaving twenty line comments. I'd fix the class of problem:ConfigureConventionsdefaults for strings and decimals, a migration review checklist, and an analyser or test that fails ifOnConfiguringcontains a connection string."
public class AppDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer("Server=prod-sql.database.windows.net;Database=Shop;User Id=app;Password=P@ssw0rd!"); // 1
options.UseLazyLoadingProxies(); // 2
}
protected override void OnModelCreating(ModelBuilder b)
{
b.Entity<Customer>().HasMany(c => c.Orders).WithOne(o => o.Customer)
.OnDelete(DeleteBehavior.Cascade); // 3
b.Entity<Order>().HasMany(o => o.Lines).WithOne().OnDelete(DeleteBehavior.Cascade);
}
}
public class Customer
{
public Guid Id { get; set; } = Guid.NewGuid(); // 4
public string Name { get; set; } // 5 (nvarchar(max))
public string Email { get; set; } // 5
public virtual ICollection<Order> Orders { get; set; } // 2 (virtual for proxies)
}
| # | Severity | Finding | Fix |
|---|---|---|---|
| 1 | Security (blocking) | Credential in source; prod server hard-coded | Rotate the password; AddDbContext + configuration; managed identity in Azure |
| 3 | Data loss (blocking) | Cascade on customer → orders | Restrict; soft delete for customers; cascade only order → lines |
| 2 | Performance (blocking for APIs) | Lazy loading proxies: N+1, cycles | Remove proxies; Include or projection |
| 4 | Performance | Random GUID clustered key | Let EF Core generate (sequential) or nonclustered PK |
| 5 | Performance / integrity | nvarchar(max), no unique email |
HasMaxLength, unique index on Email |
| — | Design | Public setters, mutable collections | Encapsulate later; not blocking |
See the code example: configuration from DI, safe delete behaviour, sequential keys, explicit lengths and conventions.
ConfigureConventions defaults, secret scanning in the pipeline (GitHub secret scanning or gitleaks), a migration checklist (lengths, delete behaviour, key strategy), and has-pending-model-changes in CI.After adopting this checklist on [a new service], the first production load test showed [2] queries per order-list request instead of the [50+] seen in a sibling service still using lazy loading, and the security review passed with no findings on data access.
Checks whether the candidate can review EF Core configuration like a senior: prioritised by risk, with concrete fixes and systemic prevention.
Green flags
Red flags
AddDbContext (Program.cs) ──► DbContextOptions<AppDbContext> ──► ctor(options)
▲
IConfiguration (appsettings, env vars, Key Vault)
OnConfiguring runs after DI options are applied; a hard-coded UseSqlServer overrides whatever the host configured, so tests and environments can't swap it. If a secret is committed, history keeps it forever: rotation is the only remedy. Azure SQL supports Entra ID authentication with managed identities (Authentication=Active Directory Default in Microsoft.Data.SqlClient), which removes the password entirely. This aligns with the ACSC Essential Eight emphasis on restricting administrative privileges and protecting credentials.
UseLazyLoadingProxies makes EF Core generate a runtime subclass of each entity (Castle.Core proxies) overriding virtual navigations. The first access to customer.Orders runs a query on the context that loaded it. In a loop or during JSON serialisation that becomes N+1. If the context is disposed, access throws, or with warnings configured, logs. The proxies also prevent sealed classes and complicate Native AOT.
GET /customers → 1 query (customers)
serializer touches c.Orders for each of 50 customers → 50 queries
serializer touches o.Customer → back-reference → cycle (or more queries)
DeleteBehavior.Cascade becomes ON DELETE CASCADE; SQL Server deletes dependents inside the same statement, taking locks on every row and potentially escalating to a table lock. SQL Server rejects multiple cascade paths to one table (error 1785).
A random GUID clustered key spreads inserts across all pages, causing page splits and fragmentation; every nonclustered index carries the 16-byte key. nvarchar(max) columns can't be index keys and inflate memory grants.
ConfigureConventions: Properties<string>().HaveMaxLength(256), Properties<decimal>().HavePrecision(18, 2).Guid.NewGuid() initialisers so EF Core's sequential generator runs.OnConfiguring overrides, or simply bans them in application DbContexts.LogTo.Guid.NewGuid() vs EF Core's default generation; compare fragmentation.gitleaks over a repo with a committed connection string.The rewritten configuration.
// Program.cs
using Microsoft.EntityFrameworkCore;
using Shop.Infrastructure;
var builder = WebApplication.CreateBuilder(args);
// Locally: user secrets. In Azure: app setting with
// "Server=tcp:shop-sql.database.windows.net;Database=Shop;Authentication=Active Directory Default;Encrypt=True"
builder.Services.AddDbContext<AppDbContext>(o =>
o.UseSqlServer(builder.Configuration.GetConnectionString("Shop"),
sql => sql.EnableRetryOnFailure()));
var app = builder.Build();
app.Run();
namespace Shop.Infrastructure;
using Microsoft.EntityFrameworkCore;
public sealed class Customer
{
public Guid Id { get; set; } // no initialiser: EF Core assigns a sequential GUID
public required string Name { get; set; }
public required string Email { get; set; }
public bool IsDeleted { get; set; } // soft delete instead of cascading hard deletes
public List<Order> Orders { get; } = []; // not virtual: no proxies
}
public sealed class Order
{
public Guid Id { get; set; }
public Guid CustomerId { get; set; }
public Customer Customer { get; set; } = null!;
public List<OrderLine> Lines { get; } = [];
}
public sealed class OrderLine
{
public int Id { get; set; }
public Guid OrderId { get; set; }
public required string Sku { get; set; }
}
public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<Customer> Customers => Set<Customer>();
public DbSet<Order> Orders => Set<Order>();
protected override void ConfigureConventions(ModelConfigurationBuilder b)
{
b.Properties<string>().HaveMaxLength(256); // no accidental nvarchar(max)
b.Properties<decimal>().HavePrecision(18, 2);
}
protected override void OnModelCreating(ModelBuilder b)
{
b.Entity<Customer>(e =>
{
e.Property(c => c.Name).HasMaxLength(200);
e.HasIndex(c => c.Email).IsUnique().HasFilter("[IsDeleted] = 0");
e.HasQueryFilter(c => !c.IsDeleted);
e.HasMany(c => c.Orders).WithOne(o => o.Customer)
.OnDelete(DeleteBehavior.Restrict); // a customer delete is a decision
});
b.Entity<Order>()
.HasMany(o => o.Lines).WithOne().HasForeignKey(l => l.OrderId)
.OnDelete(DeleteBehavior.Cascade); // composition: lines die with the order
b.Entity<OrderLine>().Property(l => l.Sku).HasMaxLength(32).IsUnicode(false);
}
}
// Loading explicitly instead of lazy loading
// var dto = await db.Customers
// .Where(c => c.Id == id)
// .Select(c => new CustomerDto(c.Id, c.Name, c.Orders.Count))
// .SingleOrDefaultAsync(ct);
OnConfiguring with UseSqlServer. Why it is wrong: it still overrides DI configuration in tests. Instead: configure only through AddDbContext.Include or projection.null, so code returns wrong results (an order with no lines, a total of zero) instead of failing loudly. Instead: search for every navigation access, project read paths to DTOs with Select, use Include for the aggregates you modify, use Entry(x).Collection(...).LoadAsync() for the rare conditional case, and add integration tests that assert the loaded data.NoAction without deciding ownership. Why it is wrong: orphan cleanup logic is lost. Instead: cascade only for compositions; soft delete or explicit deletes elsewhere.= Guid.NewGuid() initialisers on keys. Why it is wrong: EF Core sees a set key and doesn't generate one, so the random value becomes the clustered key. Instead: remove the initialiser; by convention a Guid key is ValueGeneratedOnAdd and the SQL Server provider assigns it client-side with its SequentialGuidValueGenerator, which is ordered for SQL Server's uniqueidentifier comparison.ConfigureConventions defaults.A model review is cheapest before the first migration reaches production. Afterwards each finding becomes a data migration with real costs: changing a clustered key or a column type on a large table rebuilds it and every index that carries the key, takes schema locks, needs expand/contract over several releases if you can't take downtime, and on Azure SQL can generate enough log to throttle the database. So I block on things that are expensive to change later (keys, column types, delete behaviour) as well as on security, and push the rest into conventions and automation rather than reviewers' memory.
Two details worth being exact about. Passwordless Azure SQL: Authentication=Active Directory Default is a Microsoft.Data.SqlClient feature (which the EF Core 10 SQL Server provider depends on) that uses DefaultAzureCredential, so it picks up the managed identity in Azure and your developer sign-in locally; the database also needs CREATE USER [app] FROM EXTERNAL PROVIDER with least-privilege roles. Soft delete as the cascade replacement: add a global query filter, make unique indexes filtered (WHERE IsDeleted = 0) so a deleted customer's email can be reused, decide what happens to dependents (they usually stay, hidden through the parent's filter or their own), index or filter IsDeleted so hot queries don't scan deleted rows, and keep a purge job for Privacy Act retention limits, because soft-deleted personal data is still personal data you hold.
| Finding | When it is acceptable | Cost if left | Fix |
|---|---|---|---|
OnConfiguring |
Design-time-only contexts, samples | Leaked secrets, untestable | AddDbContext + config/managed identity |
| Lazy loading | Desktop apps with long-lived contexts, prototypes | N+1, cycles | Explicit loading or projection |
| Cascade | Compositions with small fan-out | Mass deletes, 1785 errors | Restrict + soft delete |
| Random GUID clustered | Tiny tables | Fragmentation, wide indexes | Sequential or nonclustered PK |
nvarchar(max) |
Genuinely large text (notes, documents) | No index, big grants | HasMaxLength / conventions |
Measure the impact with query counts per request (Application Insights dependency count), index fragmentation, and a secret-scanning report.
A relationship has a principal (e.g. Customer) and a dependent that holds the foreign key (Order.CustomerId).
HasOne(o => o.Customer).WithMany(c => c.Orders).HasForeignKey(o => o.CustomerId).HasOne().WithOne(), and you must say which side holds the FK.EnrolledAt).Required relationships (non-nullable FK) default to cascade delete; optional ones default to ClientSetNull. The trade-off: cascades are convenient but can delete far more than intended and SQL Server refuses multiple cascade paths, so I default to Restrict for anything important.
Identity int/bigint keys are small (4/8 bytes) and always increasing, so inserts append to the end of the clustered index; the downside is the value only exists after the INSERT. GUIDs can be created anywhere (offline clients, merges, ids before saving) but are 16 bytes, and random GUIDs as a clustered key cause page splits and fragmentation.
uniqueidentifier.Guid.CreateVersion7() is time-ordered by .NET's byte order, but SQL Server compares the last 6 bytes first, so it is not sequential in a SQL Server index.HasKey(x => new { x.A, x.B })), alternate keys (unique, can be FK targets), sequences and HiLo (UseHiLo()) cover the rest.The trade-off: identity is simplest and smallest; GUIDs buy distribution at the cost of size and care with clustering.
Use Microsoft Entra ID authentication with a managed identity. Steps: 1. set a Microsoft Entra admin on the Azure SQL logical server (optionally enable Microsoft Entra-only authentication to turn off SQL logins); 2. turn on a system- or user-assigned managed identity on the App Service, Container App or AKS workload; 3. connected as the Entra admin, create a contained user for it in the database, CREATE USER [my-api] FROM EXTERNAL PROVIDER;, and grant least privilege (db_datareader, db_datawriter, no DDL for the app); 4. use a connection string with Authentication=Active Directory Default (or Active Directory Managed Identity plus User Id=<client id> for a user-assigned identity). Microsoft.Data.SqlClient gets and refreshes tokens itself, so EF Core needs no code change, and locally the same string uses your Azure CLI or Visual Studio sign-in. No secret exists to leak or rotate.
How to tell it (STAR)
**S:** At [company] a new order service was [a week] from go-live when its data layer came to me for review. **T:** I had to get it production-safe without derailing the date. **A:** I ranked the findings: a production password in `OnConfiguring` first, so we rotated it the same day and moved to managed identity; then cascade deletes that could wipe a customer's orders; then lazy loading that fired over 50 queries per list request. Because nothing was in production, I had the team regenerate the initial migration with sequential keys, real string lengths and conventions. **R:** The list endpoint dropped to [2] queries and [80 ms] p95, the security review passed, and the checklist became our standard for new services.
Last updated 23 Nov 2026.