本文介绍了在 Db Initializer 的 Seed 方法中创建 Asp.net Identity 用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先用 EF 6 代码创建了我的数据层,我通过从 DropCreateDatabaseIfModelChanges 继承的 EvInitializer 类的 Seed 方法填充数据库.Seed 方法的实现是

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
}

我的问题是如何使用 UserManager 类在 Seed 方法中添加用户.当我改变var result = awit manager.CreateAsync(user, "Temp_123");

var result = manager.CreateAsync(user, "Temp_123").Result;//或.Wait
应用程序无限期挂起

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

推荐答案

在 asp.net-identity-2 中,usermanager 有非异步方法要创建.

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

使用户成为管理员

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

正如 trailmax 评论的那样,Create() 扩展方法带有 Microsoft.AspNet.Identity 命名空间,所以不要忘记 using Microsoft.AspNet.Identity

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

这篇关于在 Db Initializer 的 Seed 方法中创建 Asp.net Identity 用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 19:36