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

📚 Interview question

Code review: an update endpoint loads the entity by id, maps the whole request DTO onto it with AutoMapper, calls db.Update(entity) and SaveChanges, and returns the entity. There is no concurrency check. What do you flag, in what order, and what does the rewrite look like?

A senior code review of an EF Core update endpoint: missing ownership check (IDOR), over-posting through whole-DTO mapping, lost updates with no RowVersion, Update() on an already-tracked entity writing every column, mapper-replaced child collections, null handling, returning entities, and the rewrite with a use-case DTO, load-check-apply-save and 409 handling.

Senior CodeReview Advanced aspnet-core change-tracking code-review concurrency ef-core over-posting

🎯 Key points

  • First: authorisation, the endpoint loads by id without checking the caller owns the record (IDOR)
  • Over-posting: mapping the whole DTO lets clients set Status, OwnerId or Budget, bypassing workflow and approval rules as well as security
  • Lost updates: no RowVersion, so the last writer silently wins; set the client's RowVersion as OriginalValue and return 409
  • Update() on an already-tracked entity is redundant and marks every column modified: bigger writes, more log and trigger work, wider conflict window
  • Mapper replacing child collections creates new instances: orphans, identity conflicts or deleted children
  • Null result → NullReferenceException → 500 instead of 404; return a response DTO, never the tracked entity
  • Rank findings by severity and mark security and data-loss items as blocking
  • Rewrite: use-case DTO, load with an ownership filter, check RowVersion, apply explicit fields, SaveChangesAsync, map DbUpdateConcurrencyException to 409

⏱ 30-second answer

I'd rank the findings by impact:

  1. Security: it loads by id with no ownership check (an IDOR), and mapping the whole DTO allows over-posting of fields like Status or OwnerId.
  2. Wrong data: no concurrency token, so concurrent edits are silently lost; and the mapper may replace child collections, orphaning or deleting lines.
  3. Waste: Update() on an already-tracked entity is redundant and marks every column modified.
  4. Robustness and design: a missing record throws a NullReferenceException (500, not 404), and it returns the entity instead of a DTO.

The rewrite: a use-case DTO with only editable fields plus RowVersion, load filtered by owner, set the RowVersion original value, assign fields explicitly, SaveChangesAsync, and map DbUpdateConcurrencyException to 409. The trade-off is a few lines of explicit mapping in exchange for correct, minimal, secure updates.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd go through it in severity order, starting with what can hurt users or leak data. The endpoint loads Projects.Find(id) with nothing tying the record to the caller, so any authenticated user can update anyone's project by changing the id: that's an insecure direct object reference, and it's the first blocking comment. Second, mapper.Map(dto, project) copies every matching property, so if the DTO has, or later gains, OwnerId, Status or Budget, a client can set them. That's over-posting, and it's why I want a DTO per use case with only editable fields, mapped explicitly.

Then correctness. There's no concurrency token, so if two people edit the same project the second save silently overwrites the first. For example, at [company] we found [project budgets being reverted] by exactly this pattern, and [adding a RowVersion surfaced around N conflicts a week that had been silent]. Also, AutoMapper mapping a Tasks collection onto a tracked entity tends to replace the collection items with new instances: EF Core sees the old tasks removed and new ones added, which either deletes and reinserts rows with new ids or throws an identity conflict.

Then waste: db.Update(project) after loading it tracked is redundant, because DetectChanges would have found the changes, and it's harmful because it marks every column modified, so every save writes the whole row, bumps every audit trigger and widens the conflict window. Lastly, Find can return null, which becomes a NullReferenceException and a 500, and returning the tracked entity leaks internal fields and can create serialisation cycles. The rewrite is short: load filtered by owner, set the client's RowVersion as the original value, assign the editable fields, save, and return 204 or 409. The line I'd leave in the review is: Update() in a handler that just loaded the entity is always a smell."


Code under review

app.MapPut("/projects/{id:int}", (int id, ProjectDto dto, AppDbContext db, IMapper mapper) =>
{
    var project = db.Projects.Include(p => p.Tasks).FirstOrDefault(p => p.Id == id); // 1 no owner filter, 6 sync
    mapper.Map(dto, project);                 // 2 whole DTO -> over-posting; 4 replaces Tasks; 5 null -> NRE
    db.Projects.Update(project);              // 3 redundant, marks every column modified
    db.SaveChanges();                         // 6 sync I/O; 7 no concurrency check
    return Results.Ok(project);               // 8 returns the tracked entity
});

public class ProjectDto                       // shared with GET; includes OwnerId, Status, Budget, Tasks
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public int OwnerId { get; set; }
    public ProjectStatus Status { get; set; }
    public decimal Budget { get; set; }
    public List<TaskDto> Tasks { get; set; } = [];
}

Findings, by severity

# Severity Finding Fix
1 Security (blocking) No ownership or tenant filter: IDOR Filter by the caller's id/tenant in the query; 404 if not found
2 Security (blocking) Whole-DTO mapping enables over-posting of OwnerId, Status, Budget Use-case DTO with only editable fields, explicit assignment
7 Wrong data (blocking) No concurrency token: lost updates [Timestamp] RowVersion, set OriginalValue, 409 on conflict
4 Wrong data (blocking) Mapper replaces Tasks with new instances Separate endpoint for tasks, or reconcile by key
5 Crash FirstOrDefault null → NullReferenceException → 500 Return 404
3 Performance / correctness Update() on a tracked entity writes every column Remove it; let DetectChanges find real changes
6 Scalability Sync FirstOrDefault/SaveChanges block thread-pool threads SingleOrDefaultAsync, SaveChangesAsync(ct)
8 Design Returns the tracked entity (leaks fields, cycles) Return 204 or a response DTO

The rewrite

See the code example: a UpdateProjectRequest with Name, Description, DueOn and RowVersion; the load filters by the caller's user id; fields are assigned explicitly; DbUpdateConcurrencyException becomes 409 with ProblemDetails.

How I'd close the review

  • Blocking: 1, 2, 4, 5, 7. These can leak or corrupt data.
  • Should fix in this PR: 3, 6, 8.
  • Follow-ups: an integration test for concurrent edits and for editing another user's project; a team rule (and a Roslyn analyser or grep check in CI) flagging .Update( and State = EntityState.Modified in handlers; AutoMapper only for read projections, if at all.

Production example

Applying this rewrite to [the project settings endpoint] cut the UPDATE from [~25 columns] to [one to three], closed a [penetration-test finding] for the IDOR, and the new 409 responses showed [about N] concurrent-edit conflicts a week that had previously overwritten data.

🔍 What the interviewer is checking

Checks whether the candidate can review EF Core write code for security, correctness and efficiency, rank findings by severity, and produce a clean rewrite.

Green flags

  • Leads with the IDOR and over-posting.
  • Spots the missing concurrency check and explains OriginalValue.
  • Explains why Update() on a tracked entity writes every column.
  • Notices the collection-mapping hazard and the null handling.

Red flags

  • Only comments on async or naming.
  • Thinks Update() is required to save changes.
  • Suggests catching the concurrency exception and saving again blindly.

📚 Learn in depth

1. Why each finding happens at the EF Core level

FirstOrDefault (tracking)  -> project + tasks tracked, snapshot taken
mapper.Map(dto, project)   -> scalar properties overwritten (including OwnerId, Status)
                           -> project.Tasks replaced with NEW TaskItem instances
Update(project)            -> State = Modified, every property flagged
                           -> graph walk: new task instances with keys -> Modified (or conflict)
SaveChanges                -> UPDATE every column of Projects, no RowVersion in WHERE

2. Update() on a tracked entity

For an entity that is already tracked, Update sets its state to Modified and marks every property modified, even those that did not change. The SQL becomes:

UPDATE [Projects] SET [Budget] = @p0, [Description] = @p1, [DueOn] = @p2,
       [Name] = @p3, [OwnerId] = @p4, [Status] = @p5
WHERE [Id] = @p6;

Without it, DetectChanges would produce SET [Name] = @p0 only.

3. Collections and mappers

When a mapper assigns a new list or new element instances to a tracked collection, EF Core treats the old elements as removed (deleted if the relationship is required, FK nulled if optional) and the new ones as added or, if they carry existing keys, as conflicting with the tracked instances. The result is lost ids, cascades or the identity-conflict exception.

4. Concurrency across the disconnect

GET  -> returns RowVersion 0x...07D1
PUT  -> client sends 0x...07D1
        entry.Property(RowVersion).OriginalValue = 0x...07D1
        UPDATE ... WHERE Id = @id AND RowVersion = 0x...07D1
        0 rows -> DbUpdateConcurrencyException -> 409

5. IDOR at the data layer

Filtering by owner in the query (p.Id == id && p.OwnerId == userId) both enforces authorisation and avoids leaking whether the id exists (always 404). Resource-based authorisation (IAuthorizationService.AuthorizeAsync(user, project, "Edit")) is the alternative when rules are richer. A global query filter for tenants complements, but does not replace, per-user ownership.

Try it yourself

  1. Reproduce the original endpoint and post a DTO that changes OwnerId; confirm it saves.
  2. Log the SQL with and without Update() and compare the SET lists.
  3. Map a DTO with tasks onto a tracked project and watch the generated DELETE/INSERT or the exception.
  4. Add a RowVersion, run two concurrent PUTs in a test and assert one gets 409.
  5. Write an integration test where user B tries to update user A's project and expects 404.

💻 Code

The rewrite: a use-case DTO, an ownership filter, explicit assignment and a concurrency check.

namespace Projects.Api;

using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;

public sealed record UpdateProjectRequest(
    [property: Required, MaxLength(200)] string Name,
    [property: MaxLength(2000)] string? Description,
    DateOnly? DueOn,
    [property: Required] byte[] RowVersion);

public sealed record ProjectResponse(int Id, string Name, string? Description, DateOnly? DueOn, byte[] RowVersion);

public static class UpdateProjectEndpoint
{
    public static async Task<IResult> HandleAsync(
        int id, UpdateProjectRequest req, ClaimsPrincipal user, AppDbContext db, CancellationToken ct)
    {
        var userId = int.Parse(user.FindFirstValue(ClaimTypes.NameIdentifier)!);

        // 1. Ownership in the query: no IDOR, and no hint whether the id exists.
        var project = await db.Projects
            .SingleOrDefaultAsync(p => p.Id == id && p.OwnerId == userId, ct);
        if (project is null) return Results.NotFound();

        // 7. The client's version is the ORIGINAL value, so it goes in the WHERE clause.
        db.Entry(project).Property(p => p.RowVersion).OriginalValue = req.RowVersion;

        // 2. Explicit, editable fields only: OwnerId, Status and Budget cannot be over-posted.
        project.Name = req.Name;
        project.Description = req.Description;
        project.DueOn = req.DueOn;

        // 3. No Update(): DetectChanges writes only the columns that changed.
        try
        {
            await db.SaveChangesAsync(ct);
        }
        catch (DbUpdateConcurrencyException)
        {
            return Results.Problem(
                title: "The project was changed by someone else.",
                detail: "Reload the project and apply your changes again.",
                statusCode: StatusCodes.Status409Conflict);
        }

        // 8. Return a DTO with the new RowVersion, never the tracked entity.
        return Results.Ok(new ProjectResponse(project.Id, project.Name, project.Description, project.DueOn, project.RowVersion));
    }
}
// Program.cs
app.MapPut("/projects/{id:int}", UpdateProjectEndpoint.HandleAsync)
   .RequireAuthorization()
   .WithName("UpdateProject");

// Model: SQL Server rowversion, generated on every write.
modelBuilder.Entity<Project>().Property(p => p.RowVersion).IsRowVersion();

⚠ Common mistakes

  • Mistake: Loading a record by id alone in an update endpoint. Why it is wrong: any authenticated user can modify any record by changing the id (IDOR, OWASP API1). Instead: filter by owner or tenant in the query, or use resource-based authorisation.
  • Mistake: Mapping a shared DTO onto the entity with AutoMapper or SetValues. Why it is wrong: every matching property is copied, so clients can set fields they should never control. Instead: a request DTO per use case and explicit assignments.
  • Mistake: Calling Update() after loading the entity tracked. Why it is wrong: it is redundant and marks every column modified, writing the whole row. Instead: just change properties and call SaveChangesAsync.
  • Mistake: No concurrency token on user-edited records. Why it is wrong: the last writer silently overwrites others. Instead: IsRowVersion(), carry it through the DTO, set OriginalValue, return 409.
  • Mistake: Letting the mapper write child collections onto a tracked aggregate. Why it is wrong: new instances replace tracked ones, causing deletes, reinserts or identity conflicts. Instead: separate endpoints for children or reconcile by key.
  • Mistake: Not handling a missing record. Why it is wrong: null flows into the mapper and becomes a 500. Instead: return 404.
  • Mistake: Returning the tracked entity from the endpoint. Why it is wrong: it exposes internal and sensitive fields and can hit serialisation cycles or lazy loads. Instead: a response DTO.
  • Mistake: Treating the review as a style nit list. Why it is wrong: security and data-loss issues get lost among minor comments. Instead: rank by severity and mark blocking items clearly.

🏛 Senior insight: trade-offs

This pattern (load, map everything, Update(), save) is common because it looks tidy and works in a single-user demo. In production it is three bugs at once: a security hole, silent data loss and wasteful writes. I review it in severity order so the security and data-loss findings are unmistakably blocking, and I push for a team convention so it doesn't come back: request DTOs per use case, explicit mapping on the write side, RowVersion on anything users edit, and Update() flagged in review.

Option When it fits Cost When not to
Explicit assignment from a use-case DTO Write endpoints A few lines per field —
AutoMapper / Mapperly for writes Large DTOs with strict, tested configuration and ignore rules Hidden over-posting risk Security-sensitive entities
RowVersion + 409 Any user-edited record One column, client must round-trip it Append-only data
ExecuteUpdate with owner filter Simple single-field updates No domain logic or interceptors When rules depend on current state

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Update() writing every column. Why: Checks the wider rules for Add, Attach and Update with disconnected entities.
    How to answer

    All three walk the whole graph and set states based on whether each entity has a key value:

    • Add: everything becomes Added, so EF Core inserts it.
    • Attach: entities with a key become Unchanged, without one become Added. Nothing is written until you change something.
    • Update: entities with a key become Modified with every property marked, because EF Core has no original values to compare with, so it writes every column.

    That makes Update dangerous for APIs: it overwrites columns the client never meant to change and silently loses concurrent edits. Better: accept a use-case DTO containing only the editable fields (so nothing can be over-posted), load the entity tracked and apply the DTO so only real changes are written, use Attach plus IsModified for a known partial update, or ExecuteUpdate for set-based changes, always with a RowVersion set as the original value. The trade-off is one extra read in exchange for correct, minimal updates.

  2. When: Candidate mentions setting the RowVersion original value. Why: Checks Entry API fluency, including conflict resolution with database values.
    How to answer

    db.Entry(entity) returns an EntityEntry<T>, the change tracker's view of one entity:

    • State, CurrentValues, OriginalValues and GetDatabaseValuesAsync() for state and values.
    • Property(p => p.X) gives CurrentValue, OriginalValue and IsModified, so you can mark one column for update, or set the RowVersion original value for a concurrency check.
    • Collection(...)/Reference(...) give explicit loading (LoadAsync, IsLoaded) and Query() to filter or count related rows without loading them all.
    • CurrentValues.SetValues(dto) copies matching values; ReloadAsync() discards local changes.

    For disconnected graphs, ChangeTracker.TrackGraph visits each node so you choose its state. The trade-off: it gives precise control, but it is easy to misuse (setting current instead of original values, or calling Entry() in hot loops).

  3. When: Candidate mentions over-posting or DTOs. Why: Checks the design case for separating DTOs from domain entities.
    How to answer

    A domain model represents business concepts with behaviour and invariants (an Order that can be paid, cancelled, and refuses invalid changes). A DTO (data transfer object) is a flat, behaviour-free contract for moving data across a boundary: an HTTP request or response, a message, a query result. Keep them separate so that the API contract and the domain can change independently, so clients cannot over-post fields they must not set (IsAdmin, Status), and so internal data does not leak in responses. Map with explicit code, source-generated mappers (Mapperly) or EF Core projections straight to DTOs for reads. Sharing one type is acceptable only for simple CRUD with no rules, and even then be careful at public boundaries.

🛠 Real-world problems: how you handle them

Project budgets reverting and a penetration-test IDOR finding
Situation
A [project management] SaaS on ASP.NET Core and Azure SQL with [~4,000] business users; a [penetration test] was due before a government customer signed, with Privacy Act obligations on customer data.
Signals
Support tickets about [budgets and due dates] reverting; audit triggers showing full-row updates for single-field edits; the pen tester changed another tenant's project name by editing the id in a PUT request.
Investigation
Reviewed the PUT endpoint: load by id with no owner filter, AutoMapper mapping a shared DTO, `Update()`, `SaveChanges`. Logged the SQL and saw every column written. Reproduced lost updates with two concurrent requests and over-posting by adding `OwnerId` to the payload.
Resolution
Immediately: added an owner filter to the query and removed sensitive fields from the mapping, deployed the same day. Then: a use-case request DTO with explicit assignment, a `RowVersion` column with 409 handling and a reload prompt in the UI, removed `Update()`, async calls, response DTOs.
Prevention
Integration tests for cross-tenant edits (expect 404) and concurrent edits (expect 409); a CI grep or analyser flagging `.Update(` in handlers; a security review checklist for write endpoints; Application Insights dashboard of 409 rates.

How to tell it (STAR)

**S:** At [company], before a [penetration test] for a government customer, we also had tickets about project budgets reverting. **T:** I reviewed the project update endpoint, which turned out to cause both. **A:** It loaded by id with no owner check, mapped the whole DTO with AutoMapper, called `Update()` and saved, with no concurrency token. I shipped an owner filter the same day, then rewrote it with a request DTO of editable fields, explicit assignment, a `RowVersion` with 409 responses and no `Update()`. **R:** The pen test finding was closed, UPDATEs dropped from [~25] columns to [one to three], and the 409s showed [about N] conflicts a week that had been silently overwriting data.

↩ Usually asked after

More in Change Tracking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me