Entity Framework Core Interview Question #108
What is a disconnected entity scenario in EF Core?
Change Tracking, Updates, Transactions & Concurrency Mid-Level Intermediate
Quick Interview Answer
A disconnected scenario occurs when an entity is read using one DbContext but later modified or submitted when that context no longer exists. ASP.NET Core web applications commonly work this way because each request typically has a separate scoped DbContext.
Detailed Explanation
A disconnected scenario occurs when an entity is read using one DbContext but later modified or submitted when that context no longer exists. ASP.NET Core web applications commonly work this way because each request typically has a separate scoped DbContext.
The new context must determine whether the submitted entity is new or existing and which properties should change.
DTOs plus explicit loading and mapping are often safer than attaching an entire client-supplied entity graph.
Code Example
var product = await db.Products.FindAsync(dto.Id);
if (product is null)
return NotFound();
product.Name = dto.Name;
product.Price = dto.Price;
await db.SaveChangesAsync();