When two operators or back-office users open the same record in an ASP.NET Core MVC form at roughly the same time, submit changes, and neither sees that the other updated the row first, silent last-write-wins overwrites destroy valid work. Holding long-lived database locks while a user fills out an HTML form is impractical across HTTP requests, which makes optimistic concurrency control the right fit for web forms.
In ASP.NET Core MVC, optimistic concurrency pairs a row-version/concurrency token (such as SQL Server rowversion / [Timestamp] or an explicit concurrency token column) with a hidden form field (<input type="hidden" asp-for="RowVersionBase64" />). When SaveChangesAsync() runs, Entity Framework Core includes the original concurrency token in the WHERE clause of the UPDATE statement. If another request modified the row in the meantime, zero rows match, EF Core throws DbUpdateConcurrencyException, and your MVC controller can reload the latest database state and render a clear row-level conflict resolution view showing both the user's submitted values and the current database values.
1. Architectural Blueprint & Conflict Resolution Flow
Plaintext
[User A opens Edit Form] ── loads Invoice (RowVersion = v1) ──> renders hidden token v1
[User B opens Edit Form] ── loads Invoice (RowVersion = v1) ──> renders hidden token v1
1. [User A submits Form (v1)]
└─> UPDATE Invoices SET ..., RowVersion = v2 WHERE Id = @id AND RowVersion = v1
└─> 1 row affected ──> Success (200 / Redirect)
2. [User B submits Form (stale v1)]
└─> UPDATE Invoices SET ..., RowVersion = v2 WHERE Id = @id AND RowVersion = v1
└─> 0 rows affected ──> DbUpdateConcurrencyException thrown
└─> Controller fetches current DB row (v2), attaches User B's attempted values,
and renders Edit view with side-by-side conflict diff & explicit resolution choice
Concurrency Strategy | Mechanism in MVC + EF Core | Best-Fit Scenario |
Pessimistic Locking | Long-held DB locks or checkout leases | High-contention seats/inventory with strict exclusive checkout; poor fit for stateless browser forms. |
Optimistic Concurrency (Token) | Concurrency token (rowversion / version column) in hidden Razor field + DbUpdateConcurrencyException handling | Standard MVC forms and back-office workflows where collisions are occasional and conflicts should be surfaced cleanly. |
Overwrite-on-Conflict (ForceOverwrite) | User explicitly confirms overwriting the newer DB row using the latest token from the conflict view | Intentional conflict resolution after inspecting side-by-side field differences. |
2. Domain Entity, ViewModels, and EF Core Configuration
Let's model an InvoiceRecord entity with a concurrency token (byte[] RowVersion mapped as a SQL Server rowversion / concurrency token), an InvoiceEditViewModel for the Razor form, and conflict comparison fields so users can inspect exact field-level differences when a collision occurs.
C#
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
public sealed class InvoiceRecord
{
public Guid Id { get; set; }
[Required, StringLength(40)]
public string InvoiceNumber { get; set; } = string.Empty;
[Required, StringLength(160)]
public string VendorName { get; set; } = string.Empty;
[Range(0.01, 999_999_999.99)]
public decimal GrossAmount { get; set; }
[Required, StringLength(32)]
public string Status { get; set; } = "Draft";
public DateTimeOffset UpdatedAtUtc { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; } = [];
}
public sealed class FieldConflictDetail
{
public string FieldName { get; init; } = string.Empty;
public string SubmittedValue { get; init; } = string.Empty;
public string CurrentDatabaseValue { get; init; } = string.Empty;
}
public sealed class InvoiceEditViewModel
{
public Guid Id { get; set; }
public string InvoiceNumber { get; set; } = string.Empty;
[Required(ErrorMessage = "Vendor name is required.")]
[StringLength(160)]
[Display(Name = "Vendor Name")]
public string VendorName { get; set; } = string.Empty;
[Range(0.01, 999_999_999.99, ErrorMessage = "Gross amount must be greater than zero.")]
[Display(Name = "Gross Amount")]
public decimal GrossAmount { get; set; }
[Required]
[StringLength(32)]
[Display(Name = "Status")]
public string Status { get; set; } = "Draft";
// Encoded concurrency token carried in a hidden form input
public string RowVersionBase64 { get; set; } = string.Empty;
// Populated only when DbUpdateConcurrencyException occurs
public bool HasConcurrencyConflict { get; set; }
public string? LatestRowVersionBase64 { get; set; }
public List<FieldConflictDetail> Conflicts { get; set; } = [];
}
public sealed class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<InvoiceRecord> Invoices => Set<InvoiceRecord>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<InvoiceRecord>(entity =>
{
entity.HasKey(x => x.Id);
entity.Property(x => x.InvoiceNumber).HasMaxLength(40).IsRequired();
entity.HasIndex(x => x.InvoiceNumber).IsUnique();
entity.Property(x => x.VendorName).HasMaxLength(160).IsRequired();
entity.Property(x => x.GrossAmount).HasColumnType("decimal(18,2)");
entity.Property(x => x.Status).HasMaxLength(32).IsRequired();
// Marks RowVersion as an optimistic concurrency token across providers
entity.Property(x => x.RowVersion)
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate();
});
}
}
3. Controller Handling DbUpdateConcurrencyException & Conflict Resolution
When DbUpdateConcurrencyException is thrown, exception.Entries contains the EntityEntry that failed to save. Calling entry.GetDatabaseValuesAsync() retrieves the current row from the database so you can compare the submitted values against the live database values and let the user choose whether to apply their changes over the latest token, discard their edits and reload, or adjust values.
C#
using System.Globalization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
[Route("invoices")]
public sealed class InvoicesController : Controller
{
private static readonly string[] AllowedStatuses = ["Draft", "PendingApproval", "Approved"];
private readonly AppDbContext _dbContext;
private readonly ILogger<InvoicesController> _logger;
public InvoicesController(AppDbContext dbContext, ILogger<InvoicesController> logger)
{
_dbContext = dbContext;
_logger = logger;
}
[HttpGet("{id:guid}/edit")]
public async Task<IActionResult> Edit(Guid id, CancellationToken cancellationToken)
{
InvoiceRecord? invoice = await _dbContext.Invoices
.AsNoTracking()
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
if (invoice is null)
{
return NotFound();
}
var vm = new InvoiceEditViewModel
{
Id = invoice.Id,
InvoiceNumber = invoice.InvoiceNumber,
VendorName = invoice.VendorName,
GrossAmount = invoice.GrossAmount,
Status = invoice.Status,
RowVersionBase64 = Convert.ToBase64String(invoice.RowVersion)
};
return View(vm);
}
[HttpPost("{id:guid}/edit")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(
Guid id,
InvoiceEditViewModel model,
string? resolutionAction,
CancellationToken cancellationToken)
{
if (id != model.Id)
{
return BadRequest();
}
// If user explicitly chose to reload latest database state
if (string.Equals(resolutionAction, "reload", StringComparison.OrdinalIgnoreCase))
{
return RedirectToAction(nameof(Edit), new { id });
}
if (!AllowedStatuses.Contains(model.Status, StringComparer.Ordinal))
{
ModelState.AddModelError(nameof(model.Status), "Selected invoice status is not valid.");
}
if (!ModelState.IsValid)
{
return View(model);
}
byte[] originalRowVersion;
try
{
originalRowVersion = Convert.FromBase64String(model.RowVersionBase64);
}
catch (FormatException)
{
ModelState.AddModelError(nameof(model.RowVersionBase64), "Invalid concurrency token.");
return View(model);
}
InvoiceRecord? invoice = await _dbContext.Invoices
.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
if (invoice is null)
{
return NotFound();
}
// Set original token so EF Core checks it during SaveChangesAsync
_dbContext.Entry(invoice).Property(x => x.RowVersion).OriginalValue = originalRowVersion;
invoice.VendorName = model.VendorName.Trim();
invoice.GrossAmount = decimal.Round(model.GrossAmount, 2, MidpointRounding.AwayFromZero);
invoice.Status = model.Status;
invoice.UpdatedAtUtc = DateTimeOffset.UtcNow;
// If user confirmed overwriting after seeing a previous conflict, advance the original token
// to the latest token they inspected so EF Core issues a valid update on the current row.
if (string.Equals(resolutionAction, "overwrite", StringComparison.OrdinalIgnoreCase) &&
!string.IsNullOrWhiteSpace(model.LatestRowVersionBase64))
{
_dbContext.Entry(invoice).Property(x => x.RowVersion).OriginalValue =
Convert.FromBase64String(model.LatestRowVersionBase64);
}
try
{
await _dbContext.SaveChangesAsync(cancellationToken);
TempData["StatusMessage"] = $"Invoice {invoice.InvoiceNumber} saved successfully.";
return RedirectToAction(nameof(Edit), new { id = invoice.Id });
}
catch (DbUpdateConcurrencyException ex)
{
_logger.LogWarning(
ex,
"Concurrency conflict detected while saving Invoice {InvoiceId}.",
id);
var entry = ex.Entries.SingleOrDefault();
var databaseValues = entry is not null
? await entry.GetDatabaseValuesAsync(cancellationToken)
: null;
if (databaseValues is null)
{
ModelState.AddModelError(
string.Empty,
"This record was deleted by another user while you were editing it.");
return View(model);
}
var dbInvoice = (InvoiceRecord)databaseValues.ToObject();
model.HasConcurrencyConflict = true;
model.LatestRowVersionBase64 = Convert.ToBase64String(dbInvoice.RowVersion);
model.InvoiceNumber = dbInvoice.InvoiceNumber;
model.Conflicts = BuildConflictDetails(model, dbInvoice);
ModelState.AddModelError(
string.Empty,
$"Another user modified this invoice (updated at {dbInvoice.UpdatedAtUtc:u}). Review the differences below before saving.");
return View(model);
}
}
private static List<FieldConflictDetail> BuildConflictDetails(
InvoiceEditViewModel submitted,
InvoiceRecord currentDb)
{
var diffs = new List<FieldConflictDetail>();
if (!string.Equals(submitted.VendorName.Trim(), currentDb.VendorName, StringComparison.Ordinal))
{
diffs.Add(new FieldConflictDetail
{
FieldName = "Vendor Name",
SubmittedValue = submitted.VendorName.Trim(),
CurrentDatabaseValue = currentDb.VendorName
});
}
if (decimal.Round(submitted.GrossAmount, 2, MidpointRounding.AwayFromZero) != currentDb.GrossAmount)
{
diffs.Add(new FieldConflictDetail
{
FieldName = "Gross Amount",
SubmittedValue = submitted.GrossAmount.ToString("0.00", CultureInfo.InvariantCulture),
CurrentDatabaseValue = currentDb.GrossAmount.ToString("0.00", CultureInfo.InvariantCulture)
});
}
if (!string.Equals(submitted.Status, currentDb.Status, StringComparison.Ordinal))
{
diffs.Add(new FieldConflictDetail
{
FieldName = "Status",
SubmittedValue = submitted.Status,
CurrentDatabaseValue = currentDb.Status
});
}
return diffs;
}
}
4. Razor View with Hidden Concurrency Token & Side-by-Side Conflict Diff (Views/Invoices/Edit.cshtml)
The Razor view preserves the user's submitted values in the form inputs while displaying a clear comparison table (Submitted Value vs. Current Database Value) and explicit resolution buttons whenever HasConcurrencyConflict is true.
Razor CSHTML
@model InvoiceEditViewModel
@{
ViewData["Title"] = $"Edit Invoice {Model.InvoiceNumber}";
}
<section class="invoice-editor">
<h2>Edit Invoice @Model.InvoiceNumber</h2>
@if (TempData["StatusMessage"] is string statusMessage)
{
<div class="alert alert-success" role="status">@statusMessage</div>
}
<div asp-validation-summary="ModelOnly" class="alert alert-danger" role="alert"></div>
@if (Model.HasConcurrencyConflict)
{
<div class="conflict-panel" role="region" aria-label="Concurrency Conflict Details">
<h3>Row-Level Conflict Detected</h3>
<p>
<strong>Latest Database Update (UTC):</strong>
<span>@Model.LatestRowVersionBase64</span>
</p>
@if (Model.Conflicts.Count > 0)
{
<table class="conflict-table">
<thead>
<tr>
<th>Field</th>
<th>Your Submitted Value</th>
<th>Current Database Value</th>
</tr>
</thead>
<tbody>
@foreach (var diff in Model.Conflicts)
{
<tr>
<td>@diff.FieldName</td>
<td>@diff.SubmittedValue</td>
<td>@diff.CurrentDatabaseValue</td>
</tr>
}
</tbody>
</table>
}
</div>
}
<form asp-action="Edit" asp-route-id="@Model.Id" method="post">
@Html.AntiForgeryToken()
<input type="hidden" asp-for="Id" />
<input type="hidden" asp-for="InvoiceNumber" />
<input type="hidden" asp-for="RowVersionBase64" />
<input type="hidden" asp-for="LatestRowVersionBase64" />
<div class="form-group">
<label asp-for="VendorName"></label>
<input asp-for="VendorName" class="form-control" />
<span asp-validation-for="VendorName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="GrossAmount"></label>
<input asp-for="GrossAmount" type="number" step="0.01" class="form-control" />
<span asp-validation-for="GrossAmount" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Status"></label>
<select asp-for="Status" class="form-control">
<option value="Draft">Draft</option>
<option value="PendingApproval">Pending Approval</option>
<option value="Approved">Approved</option>
</select>
<span asp-validation-for="Status" class="text-danger"></span>
</div>
<div class="form-actions">
@if (Model.HasConcurrencyConflict)
{
<button type="submit" name="resolutionAction" value="overwrite" class="btn btn-warning">
Overwrite Database With My Edits
</button>
<button type="submit" name="resolutionAction" value="reload" class="btn btn-secondary">
Discard My Edits & Reload Latest
</button>
}
else
{
<button type="submit" name="resolutionAction" value="save" class="btn btn-primary">
Save Changes
</button>
}
</div>
</form>
</section>
5. Program.cs Wiring and End-to-End Integration Test
Application Setup (Program.cs)
C#
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddControllersWithViews();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
public partial class Program { }
Integration Test Verifying Stale Token Conflict (WebApplicationFactory<Program>)
C#
using System.Net;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
public sealed partial class InvoiceConcurrencyFormTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public InvoiceConcurrencyFormTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task EditPost_WithStaleConcurrencyToken_RendersConflictDiffAndPreservesSubmittedValue()
{
Guid invoiceId;
using (IServiceScope scope = _factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.EnsureCreatedAsync();
var invoice = new InvoiceRecord
{
Id = Guid.NewGuid(),
InvoiceNumber = $"INV-{Guid.NewGuid():N}"[..14],
VendorName = "Initial Vendor Ltd",
GrossAmount = 500.00m,
Status = "Draft",
UpdatedAtUtc = DateTimeOffset.UtcNow,
RowVersion = [0, 0, 0, 0, 0, 0, 0, 1]
};
db.Invoices.Add(invoice);
await db.SaveChangesAsync();
invoiceId = invoice.Id;
}
using HttpClient client = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
// GET edit form and extract antiforgery token
HttpResponseMessage getResponse = await client.GetAsync($"/invoices/{invoiceId}/edit");
getResponse.EnsureSuccessStatusCode();
string html = await getResponse.Content.ReadAsStringAsync();
string? antiForgeryToken = ExtractRequestVerificationToken(html);
Assert.False(string.IsNullOrWhiteSpace(antiForgeryToken));
// Simulate stale form submission carrying an outdated RowVersion token
string staleTokenBase64 = Convert.ToBase64String([0, 0, 0, 0, 0, 0, 0, 1]);
var formData = new Dictionary<string, string>
{
["__RequestVerificationToken"] = antiForgeryToken!,
["Id"] = invoiceId.ToString(),
["InvoiceNumber"] = "INV-TEST",
["VendorName"] = "User B Proposed Vendor",
["GrossAmount"] = "750.00",
["Status"] = "PendingApproval",
["RowVersionBase64"] = staleTokenBase64,
["resolutionAction"] = "save"
};
using var content = new FormUrlEncodedContent(formData);
HttpResponseMessage postResponse = await client.PostAsync($"/invoices/{invoiceId}/edit", content);
Assert.Equal(HttpStatusCode.OK, postResponse.StatusCode);
string conflictHtml = await postResponse.Content.ReadAsStringAsync();
Assert.Contains("Row-Level Conflict Detected", conflictHtml);
Assert.Contains("User B Proposed Vendor", conflictHtml);
}
private static string? ExtractRequestVerificationToken(string html)
{
Match match = TokenRegex().Match(html);
return match.Success ? match.Groups[1].Value : null;
}
[GeneratedRegex("""name="__RequestVerificationToken"[^>]*value="([^"]+)""", RegexOptions.IgnoreCase)]
private static partial Regex TokenRegex();
}
(Note: When testing real rowversion byte increments in SQL Server, use a SQL Server instance or Testcontainers SQL Server so the database advances the rowversion column on every UPDATE.)
6. Conclusion
Optimistic concurrency control with hidden concurrency tokens and structured conflict-resolution views protects ASP.NET Core MVC forms from silent overwrites without holding long-lived database locks across user think time. By validating the token during SaveChangesAsync(), catching DbUpdateConcurrencyException, surfacing field-level differences alongside the user's submitted values, and offering explicit reload or confirmed overwrite paths, your MVC forms handle concurrent edits safely and transparently.
Join the conversation! Your thoughts help the community grow.