简体   繁体   中英

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?

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>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM