Is there a concept of scope or nested contexts within EF Core DbContext?

c# entity-framework entity-framework-core

Question

Let's say my application's DbContest is scoped to the http request. The way I would do it normally is any method that needs to make changes, simply makes changes to objects loaded up via DbContext. Then at the end of the http request, I call SaveChangesAsync to ensure all changes in the change tracker are applied at once on a transaction.

However, what if in the middle of that I want to fire a separate save - maybe its an update to a cached value - I would like to fire that save without everything else in the change tracker coming along for the ride. Is there some way of creating a "sub-context" or nested context, or whatever the concept would be called that would allow me to do that?

1
0
3/19/2020 3:33:08 AM

Accepted Answer

In your case you can create new scope and resolve DbContext there

using (var scope = HttpContext.RequestServices.GetService<IServiceScopeFactory>().CreateScope())
using (var dbContext = scope.ServiceProvider.GetRequiredService<DBData>())
{
}
1
3/19/2020 11:25:59 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow