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.
I'd rank the findings by impact:
Status or OwnerId.Update() on an already-tracked entity is redundant and marks every column modified.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.
"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,StatusorBudget, 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
Taskscollection 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, becauseDetectChangeswould 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,Findcan return null, which becomes aNullReferenceExceptionand 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'sRowVersionas 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."
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; } = [];
}
| # | 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 |
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.
.Update( and State = EntityState.Modified in handlers; AutoMapper only for read projections, if at all.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.
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
OriginalValue.Update() on a tracked entity writes every column.Red flags
Update() is required to save changes.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
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.
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.
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
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.
OwnerId; confirm it saves.Update() and compare the SET lists.RowVersion, run two concurrent PUTs in a test and assert one gets 409.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();
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.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.IsRowVersion(), carry it through the DTO, set OriginalValue, return 409.null flows into the mapper and becomes a 500. Instead: return 404.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 |
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.
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).
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.
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.
Last updated 23 Nov 2026.