在我的 ASP.Net MVC 5 项目中,我有一个自定义初始化程序类:
class CustomInitializer : DropCreateDatabaseIfModelChanges<GhazanetContext>
我想为几个用户播种上下文。问题是新的 MVC 5 是async
并且我尝试做的任何事情都失败了。这是我尝试创建用户的代码:
private void AddRestaurant(RegisterRestaurantViewModel model, DBContext db)
{
User user = new User(model.UserName) { Addresses = new List<Address>(), Role = "Restaurant" };
user.Addresses.Add(model.Address);
Task.Factory.StartNew(async () =>
{
await Users.Create(user); // GETS STUCK HERE
var newUser = db.Users.Where(u => u.UserName == user.UserName).FirstOrDefault();
var restaurant = new Restaurant(model) { User = newUser };
db.Restaurants.Add(restaurant);
db.SaveChanges();
await Secrets.Create(new UserSecret(model.UserName, model.Password));
await Logins.Add(new UserLogin(user.Id, IdentityConfig.LocalLoginProvider, model.UserName));
const string role = "Restaurant";
if (!await Roles.RoleExists(role))
await Roles.CreateRole(new Role(role));
await Roles.AddUserToRole(role, user.Id);
}).RunSynchronously();
}
}
当我运行此代码时,它卡在上面的行中,但是当我在网站上运行它并注册用户时,它运行良好。我在这里缺少什么吗?