Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use UserManager synchronously? [duplicate]

In one of my IDatabaseInitializer in Seed method given my DbContext I insert initial data to DB. Among other things there are some users to be initialized. But as far as I use Microsoft.AspNet.Identity.EntityFramework.UserStore with Microsoft.AspNet.Identity.UserManager which has only asynchronous methods it makes DbUpdateConcurrencyException as follows:

private static void CreateUser(DbContext context, string[] roles, string userName, string userEmail) {

    // given context is 
    var user = new ApplicationUser { /* ... fields init */  };

    var userStoreAdapter = new ApplicationUserRepository(context);
    var manager = new UserManager<ApplicationUser>(userStoreAdapter);

    // pass the creation to manager by calling it synchronously. See UserManagerExtensions
    manager.Create(user, Domain.Constants.DefaultPassword);
    manager.AddToRoles(user.Id, roles);

    context.SaveChanges(); // throws DbUpdateConcurrencyException. See another approach below.
}

So the question is if there is a way to use UserManager with DbContext without concurrency issues?

I've tried the following approach taken from Optimistic Concurrency Patterns but that does not create users:

bool isSaved = true;
do
{
    try
    {
        context.SaveChanges();
        isSaved = true;
    }
    catch (DbUpdateConcurrencyException ex)
    {
        foreach (var entry in ex.Entries)
        {
            entry.Reload();
        }
        isSaved = false;
    }
} while (!isSaved);
like image 242
Artyom Avatar asked Sep 29 '15 14:09

Artyom


People also ask

How do you call asynchronous method from synchronous method in C?

Solution C In that case, you could start the async method on the thread pool: var task = Task. Run(async () => await MyAsyncMethod()); var result = task. WaitAndUnwrapException();


1 Answers

var result = Task.Run(() => {
   /*whatever you want here*/
}).Result;

// Do whatever u want with the result after
like image 179
Massaynus Avatar answered Oct 13 '22 10:10

Massaynus