CodexBloom - Programming Q&A Platform

C# 11 and Entity Framework Core 7: how to to Track Changes on Detached Entities During Bulk Update

πŸ‘€ Views: 213 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
entity-framework-core c# bulk-update C#

I'm writing unit tests and I've looked through the documentation and I'm still confused about I'm working on a C# 11 application utilizing Entity Framework Core 7 for data access... I've encountered an scenario while performing bulk updates on a collection of detached entities. After retrieving a list of entities from the database and modifying them, I'm trying to apply the changes back to the context using the `UpdateRange()` method. However, it seems that the changes are not being detected, and the entities aren't being updated in the database. Here’s the relevant part of my code: ```csharp using (var context = new MyDbContext()) { var detachedEntities = context.MyEntities.AsNoTracking().ToList(); foreach (var entity in detachedEntities) { entity.SomeProperty = "New Value"; } context.UpdateRange(detachedEntities); var result = context.SaveChanges(); } ``` Despite calling `UpdateRange()`, I receive the following warning message: `Warning: The entity is not being tracked by the context, and therefore changes want to be detected.` I’ve verified that `detachedEntities` indeed contains the modified objects. I've also tried attaching each entity individually using `context.Attach(entity)` before calling `UpdateRange()`, but that resulted in no changes being detected either. Additionally, I set the `EntityState` manually: ```csharp foreach (var entity in detachedEntities) { context.Entry(entity).State = EntityState.Modified; } ``` This didn't resolve the scenario. Is there a preferred approach for bulk updating detached entities in EF Core, or is there something I might be missing in my implementation? Any help would be appreciated! I'm coming from a different tech stack and learning C#. Any pointers in the right direction?