Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent ASP.NET Identity's UserManager from automatically saving

I'm attempting to integrate with ASP.NET Identity and its UserManager. I have my own custom user object which I've added to the out-of-the-box ApplicationUser. UserManager has a Create() method (actually it's in the UserManagerExtensions class) that creates a new user. The problem is that it automatically saves the changes to the database which is confirmed here. I've like to do some other operations in the same "transaction" before saving the new user so I can't have UserManager automatically save changes.

The interesting thing is that I'm overriding the SaveChange() method in the DbContext I'm associating to the UserManager, yet it never breaks in that method for the automatic save in Create().

Is there any way to configure UserManager to not automatically save changes.

like image 492
im1dermike Avatar asked Mar 15 '23 21:03

im1dermike


1 Answers

This feature already has been implemented in default UserStore. Therefore you just need to configure it. In ApplicationUserManager.Create() static method, or anywhere you are instantiating UserStore, set AutoSaveChanges to false.

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

    // rest of codes
}
like image 74
Sam FarajpourGhamari Avatar answered Apr 07 '23 06:04

Sam FarajpourGhamari