Creating Identity user in Seed method of Db Initializer entity-framework entity-framework-6

Accepted Answer

Usermanager in can be created using non-async methods.

var user = new ApplicationUser { Email = "", UserName = "" };
manager.Create(user, "Temp_123");

If you wish to create a "admin" role, use rolemanager similarly.

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
roleManager.Create(new Role("admin"));

Adminize the user

manager.AddToRole(user.Id, "admin");

Correction: As trailmax statedCreate() extension approach includesMicrosoft.AspNet.Identity namespace, so remember thatusing Microsoft.AspNet.Identity

12/4/2015 7:44:42 AM

Popular Answer

TMG is right; there are non-async solutions available, and in this particular situation, they are the simplest.

In general, though, you can construct a task and wait for it synchronously when you only have access to an async version of a function and you can't change the method's implementation to be async.

Thus, in place of

IdentityResult result = await manager.CreateAsync(user, "Temp_123");

You can code:

Task<IdentityResult> createTask = manager.CreateAsync(user, "Temp_123");

The IdentityResult is returned in the Wait when it has completed.


Additionally, you may set a timeout for the Wait as follows:

Task<IdentityResult> createTask = manager.CreateAsync(user, "Temp_123");
if (!createTask.Wait(5000)) // Wait up to 5 seconds
   // We've timed out waiting - Do some error handling
else if (!createTask.Result.Succeeded)
  // Creating the user failed - Do some error handling

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow