首页 > 解决方案 > .NET Core 2.1 中的 UserManager 的 AutoSaveChanges

问题描述

我想禁用 UserManager 的自动 SaveChanges 方法调用。我发现可以通过设置 UserStore 的 AutoSaveChanges 属性来实现。但是 .NET Core 2.1 中此类事情的最佳实践是什么?是否可以通过配置 IdentityBuilder 在 Startup.cs 中执行?

标签: c#.netasp.net-web-apiasp.net-core

解决方案


您需要在构造函数中创建一个继承 formMicrosoft.AspNetCore.Identity.EntityFrameworkCore.UserStore<IdentityUser>并设置AutoSaveChangesfalse的类,然后将该类注册到IServiceCollectionbefore AddEntityFrameworkStores

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

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

推荐阅读