Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserManager's AutoSaveChanges in .NET Core 2.1

I would like to disable automatic SaveChanges method calls of UserManager. I've found that it is possible to do it by setting AutoSaveChanges property of UserStore. But what is the best practice for such things in .NET Core 2.1? Is it possible to do in Startup.cs by configuring IdentityBuilder?

like image 890
idealser Avatar asked Oct 23 '25 18:10

idealser


1 Answers

You need to create a class that inherits form Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore<IdentityUser> and set AutoSaveChanges to false in the constructor and then register this class to IServiceCollection before AddEntityFrameworkStores.

public class CustomUserStore : UserStore<IdentityUser>
{
    public CustomUserStore(ApplicationDbContext context)
        : base(context)
    {
        AutoSaveChanges = false;
    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IUserStore<IdentityUser>, CustomUserStore>();

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));

    services.AddDefaultIdentity<IdentityUser>()
        .AddDefaultUI(UIFramework.Bootstrap4)
        .AddEntityFrameworkStores<ApplicationDbContext>();
}
like image 141
Kahbazi Avatar answered Oct 26 '25 08:10

Kahbazi