Drakoumel Drakoumel - 1 month ago 12
ASP.NET (C#) Question

.Net EF core DbContext.Save() during multiple Async functions

I am being puzzled with how dbcontext.SaveChanges(). Based on documentation SaveChanges() should save all the changes made to the Database.

Consider the case in which I have multiple Async functions from which all of them target different tables. If all of them try to create new entries but some take longer than others (due to computation processing etc) will the First function to reach dbcontext.SaveChanges() save all changes made by other Async functions regardless if those functions have reached the SaveChanges part?

So my concern is that during multiple Async functions data will be saved prior to the BusinessFlow just because another function said SaveChanges().

Is this the case or do they create some internal transaction scope for each async?

Startup.cs can be found here https://github.com/drakoumel/DatacircleAPI/blob/master/Startup.cs

Evk Evk
Answer

So to understand how all that will behave, you need to know how and with which lifetimes your context and repositories are registered in DI container.

Context is registered like this:

services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(Configuration["ConnectionStrings:DefaultConnection"]));

If you will look at arguments of AddDbContext method, you will see that it has contextLifetime argument, with default value of ServiceLifetime.Scoped. So context is registered with Scoped lifetime.

Repositories are registered as

services.AddScoped<IDatasourceRepository, DatasourceRepository>();

So, also with Scoped lifetime. What scoped lifetime means? It just means new object is created per request when resolving at DI container. So now you know that you have single instance of your repositories and your context per request, and as such, different calls to your controller actions use different instances of context, so their SaveChanges cannot interfere with each other.