UserManager添加角色
问题描述:
我正在尝试构建简单的方法(只是为了测试它是如何工作的),它会授予我(当前用户)一个新角色(我现在只有1个角色,所以我可以通过简单查询)UserManager添加角色
public ActionResult Index()
{
using (var db = new MyDbContext())
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
var id = User.Identity.GetUserId();
var role = db.AspNetRoles.First();
manager.AddToRole(id, role.Name);
}
return View();
}
我收到此错误:The entity type ApplicationUser is not part of the model for the current context.
上manager.AddToRole(id, role.Name);
线。我是ASP.NET的新手,所以我不太了解它的基础结构,但是这个代码在有关用户注册的问题中被提及了很多次(这里是堆栈)。
顺便说一下,作为我的目标,我必须实施角色系统以使用数据库优先迁移系统进行项目,这个manager.AddToRole(id, role.Name);
代码会在我的数据库中添加记录吗?
答
下面是一个存根(不完全),显示增加一个新创建的用户角色:
DbContext context = db;
IdentityResult ir;
var um = new UserManager<ApplicationUser>(
new UserStore<ApplicationUser>(context));
ApplicationUser au = new ApplicationUser();
au = db.Users.FirstOrDefault(u => u.UserName == uname);
if (au == null)
{
// add the user
var user = new ApplicationUser()
{
UserName = TrustNoOne("name", uname),
Email = TrustNoOne("email", uemail),
ProperUserName = TrustNoOne("propername", upropname)
};
// create a password for the user
ir = um.Create(user, upass);
// assign the user to a role
if (User.IsInRole(urole) != true)
{
ir = um.AddToRole(user.Id, urole);
}
}
请注意,UNAME,uemail,upropname,upass和urole传递给方法,其中的参数此代码生活。此外,您可以忽略TrustNoOne位(这只是我使用的)。
什么是HRMEntities?它是从什么继承的? – DavidG
你没有任何机会将您的ApplicationUser表重命名为自定义,是吗?此外,就像DavidG所暗指的那样,您确定您的HRMEntities数据库上下文是从IdentityDbContext继承的吗? –
Overhed
Sry,还没有修复它是我的连接字符串的名称。将其更改为“MyDbContext”。 – rainbowShiningUnicorn