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