📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Code review: a new service's DbContext sets the connection string in OnConfiguring, turns on lazy loading proxies, leaves every string unconfigured, keeps cascade delete on every relationship and uses Guid.NewGuid() clustered primary keys. What do you flag, in what order, and what does the fixed configuration look like?

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.

Senior CodeReview Advanced cascade-delete code-review ef-core lazy-loading model-configuration security

🎯 Key points

  • Secret in OnConfiguring is a security finding: move to configuration, Key Vault or Entra ID auth, AddDbContext in Program.cs
  • Lazy loading proxies cause hidden N+1 queries and JSON serialisation cycles; prefer explicit Include/projection
  • Cascade delete everywhere risks mass deletes and SQL Server multiple-cascade-path errors; Restrict for business data
  • Guid.NewGuid() clustered keys fragment the index; sequential GUIDs or nonclustered PK
  • Unconfigured strings become nvarchar(max): no index keys, bigger memory grants
  • Rank by severity: security → data loss → performance → design
  • Fix systemically: ConfigureConventions defaults, analysers, migration review checklist

⏱ 30-second answer

I rank findings by severity:

  1. Connection string in 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.
  2. Cascade delete everywhere: one delete can wipe thousands of rows; use Restrict for business data.
  3. Lazy loading proxies: hidden N+1 queries and serialisation cycles in an API; use Include or projection.
  4. Guid.NewGuid() clustered keys: page splits and fragmentation; let EF Core generate sequential GUIDs or make the PK nonclustered.
  5. Unconfigured strings: 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 for AddDbContext in Program.cs reading from configuration, and in Azure, Authentication=Active Directory Default with 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 UseLazyLoadingProxies and 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 are nvarchar(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: ConfigureConventions defaults for strings and decimals, a migration review checklist, and an analyser or test that fails if OnConfiguring contains a connection string."


Code under review

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)
}

Findings by severity

# 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

The rewrite

See the code example: configuration from DI, safe delete behaviour, sequential keys, explicit lengths and conventions.

How I'd close the review

  • Blocking: 1 (and rotate the secret today), 2, 3.
  • Should fix in this PR: 4 and 5, since changing keys and column types later needs a data migration.
  • Follow-up ticket: encapsulation of collections.
  • Systemic: 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.

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can review EF Core configuration like a senior: prioritised by risk, with concrete fixes and systemic prevention.

Green flags

  • Puts the credential leak first and asks for rotation
  • Explains lazy loading N+1 and cycles
  • Distinguishes composition cascades from business-entity deletes
  • Proposes conventions, scanning and checklists

Red flags

  • Treats all findings as equal nits
  • Misses the security issue
  • Suggests disabling cascade everywhere without thought

📚 Learn in depth

1. Why OnConfiguring with a literal is wrong

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.

2. How lazy loading proxies work

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)

3. Cascade delete mechanics

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).

4. Key and string physical design

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.

5. Systemic fixes

  • ConfigureConventions: Properties<string>().HaveMaxLength(256), Properties<decimal>().HavePrecision(18, 2).
  • Remove Guid.NewGuid() initialisers so EF Core's sequential generator runs.
  • An architecture test that scans OnConfiguring overrides, or simply bans them in application DbContexts.

Try it yourself

  1. Turn on lazy loading, serialise 50 customers with orders, and count queries with LogTo.
  2. Replace with a projection to DTOs and count again.
  3. Insert 500k rows with Guid.NewGuid() vs EF Core's default generation; compare fragmentation.
  4. Run gitleaks over a repo with a committed connection string.
  5. Configure two cascade paths and apply the migration to see error 1785.

💻 Code

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);

⚠ Common mistakes

  • Mistake: Treating a committed connection string as a style nit. Why it is wrong: it is a credential leak that survives in git history. Instead: block the PR, rotate, use managed identity.
  • Mistake: Removing the literal but keeping OnConfiguring with UseSqlServer. Why it is wrong: it still overrides DI configuration in tests. Instead: configure only through AddDbContext.
  • Mistake: Turning lazy loading on "for convenience" in an API. Why it is wrong: hidden N+1 and serialisation cycles. Instead: Include or projection.
  • Mistake: Removing lazy loading without auditing the code that relied on it. Why it is wrong: navigations that used to load silently are now empty collections or 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.
  • Mistake: Switching every relationship to NoAction without deciding ownership. Why it is wrong: orphan cleanup logic is lost. Instead: cascade only for compositions; soft delete or explicit deletes elsewhere.
  • Mistake: Keeping = 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.
  • Mistake: Fixing column lengths one property at a time across PRs. Why it is wrong: new properties repeat the problem. Instead: ConfigureConventions defaults.
  • Mistake: Leaving dozens of line comments without priorities. Why it is wrong: the author fixes the easy nits and misses the blockers. Instead: rank by severity and mark blocking clearly.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate discusses cascade delete. Why: Checks depth on relationships and delete behaviour.
    How to answer

    A relationship has a principal (e.g. Customer) and a dependent that holds the foreign key (Order.CustomerId).

    • One-to-many: HasOne(o => o.Customer).WithMany(c => c.Orders).HasForeignKey(o => o.CustomerId).
    • One-to-one: HasOne().WithOne(), and you must say which side holds the FK.
    • Many-to-many: two collection skip navigations; EF Core creates the join table. Use an explicit join entity when the link has data (e.g. 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.

  2. When: Candidate discusses GUID clustered keys. Why: Checks depth on key strategy.
    How to answer

    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.

    • EF Core's SQL Server provider generates sequential GUIDs client-side by default, ordered the way SQL Server compares 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.
    • Composite keys (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.

  3. When: Candidate mentions managed identity or Key Vault. Why: Checks secure production configuration.
    How to answer

    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.

🛠 Real-world problems: how you handle them

A new service ships with a production password in its DbContext
Situation
A team at [company] built a new order service on .NET 10 and EF Core 10 targeting Azure SQL in Australia East; the first pull request for the data layer came to me for review [a week] before go-live.
Signals
Pipeline secret scanning flagged a high-entropy string in `AppDbContext.cs`; a load test of the order list endpoint showed [50+] SQL dependencies per request in Application Insights.
Investigation
Read the DbContext: literal connection string with a SQL login in `OnConfiguring`, `UseLazyLoadingProxies`, cascade on all relationships, `Guid.NewGuid()` key initialisers and no string lengths. Generated the migration and confirmed `nvarchar(max)` columns and `ON DELETE CASCADE` from customers to orders. Counted queries with `LogTo` on the list endpoint.
Resolution
Immediately rotated the SQL login password and removed it from history; switched to a managed identity with `Authentication=Active Directory Default`. Then removed lazy loading in favour of projections, set `Restrict` on customer → orders with soft delete, removed key initialisers, and added `ConfigureConventions` defaults. Regenerated the initial migration since nothing was in production yet.
Prevention
Secret scanning as a required check; a data-layer review checklist (config, keys, lengths, delete behaviour, loading strategy); `has-pending-model-changes` in CI; an architecture test that forbids `OnConfiguring` in application contexts.

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.

↩ Usually asked after

More in EF Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me