I have a header and detail table and I'm looping through it and inserting the data in batch. If any exception occur then i'm doing rollback the transcation however dbcontext is not resetting as while looping through other records it's giving conflict message for identity column. What is the approach to reset the dbcontext when we rollback the transaction.
Loading

Jignesh KumarPosted Dec 12, 2024, 4:05 AM
Hello Alpesh,
If your application uses dependency injection, it's easier and less error-prone to let the DI container manage the
DbContext. This way, you don’t need to manually dispose of or recreate the context, as it will automatically create a new instance for each request or operation.Note : If you're using DI, ensure that the
DbContextis scoped per request (in web applications) or per operation in long-running applications, to avoid potential issues with shared contexts.Jaimin ShethiyaPosted Dec 10, 2024, 3:26 AM
Hello,
Use below code for reset the context in your application.
Thanks
Jaish MathewsPosted Dec 9, 2024, 4:45 PM
When using Entity Framework Core with transactions, rolling back a transaction does not reset the
DbContextstate. If you encounter an exception and rollback, theDbContextmight still track the entities that were part of the transaction, which can lead to issues like identity column conflicts.Here are approaches to handle this issue and reset the
DbContextproperly:1. Detach All Tracked Entities
After rolling back the transaction, you can detach all tracked entities from the
DbContext. This will ensure that theDbContextno longer tracks any entities, clearing its internal state.2. Use a New
DbContextInstanceAnother approach is to create a new instance of
DbContextfor each batch. This isolates each operation and ensures theDbContextstate is reset for each batch.3. Clear the
ChangeTrackerIf you prefer not to create a new
DbContextinstance, you can clear theChangeTrackerafter rolling back.Summary
DbContextbut clear tracked entities.DbContext: Use this for full isolation, but it may incur slightly more overhead.DbContextstate.Each approach has trade-offs depending on your application's requirements for performance and isolation. For most use cases, clearing the
ChangeTrackeror using a newDbContextare preferred for simplicity and robustness.Amit MohantyPosted Dec 9, 2024, 11:44 AM
You can dispose of the current DbContext instance and create a new one.
Example: