防止ASP.NET Identity的UserManager自动保存

im1*_*ike 3 c# asp.net asp.net-identity asp.net-identity-2

我正在尝试与ASP.NET Identity及其UserManager集成.我有自己的自定义用户对象,我已经添加到开箱即用的ApplicationUser中.UserManager有一个Create()方法(实际上它在UserManagerExtensions类中),用于创建新用户.问题是它会自动将更改保存到此处确认的数据库中.我想在保存新用户之前在同一个"事务"中执行其他操作,因此我无法让UserManager自动保存更改.

有趣的是,我正在重写DbContext中的SaveChange()方法,我正在关联到UserManager,但它永远不会在Create()中自动保存的方法中断.

有没有办法将UserManager配置为不自动保存更改.

Sam*_*ari 6

此功能已默认实施UserStore.因此,您只需要配置它.在ApplicationUserManager.Create()静态方法或您要实例化的任何位置UserStore,设置AutoSaveChangesfalse.

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
{
    var manager = new ApplicationUserManager(
        new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()) 
             { AutoSaveChanges = false });

    // rest of codes
}
Run Code Online (Sandbox Code Playgroud)