Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Asp.net Identity user in Seed method of Db Initializer

I have created my data layer with EF 6 code first and I am populating the db through Seed method of EvInitializer class inheriting from DropCreateDatabaseIfModelChanges. The implementation of Seed method is

protected override void Seed(EvContext context)
{
   //Add other entities using context methods
   ApplicationUserManager manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));
   var user = new ApplicationUser { Email = "[email protected]" ,UserName = "[email protected]"};
   var result = await manager.CreateAsync(user, "Temp_123");//this line gives error. obviously await cannot be used in non- async method and I cannot make Seed async
}

My question is how I can add a user in Seed method using UserManager class. when I change var result = awit manager.CreateAsync(user, "Temp_123");
to
var result = manager.CreateAsync(user, "Temp_123").Result; //or .Wait
the application hangs indefinitely

like image 695
Muhammad Adeel Zahid Avatar asked Dec 16 '14 06:12

Muhammad Adeel Zahid


People also ask

What is seeding in ASP NET?

Seed data is data that you populate the database with at the time it is created. You use seeding to provide initial values for lookup lists, for demo purposes, proof of concepts etc.


1 Answers

In asp.net-identity-2 usermanager has non async methods to create.

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

Same for rolemanager if you want to create "admin" role.

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

make the user admin

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

Edit: As trailmax commented, Create() extension method comes in with Microsoft.AspNet.Identity namespace so do not forget using Microsoft.AspNet.Identity

like image 179
tmg Avatar answered Sep 20 '22 13:09

tmg