我正在尝试构建简单的方法(只是为了测试它是如何工作的),它将授予我(当前用户)一个新角色(我现在只有一个角色,所以我可以通过简单的查询获得它)
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();
}我收到这个错误:manager.AddToRole(id, role.Name);行上的The entity type ApplicationUser is not part of the model for the current context.。我是ASP.NET的新手,所以我对它的基础设施了解不多,但是这段代码在关于用户注册的问题中被提到了很多次(在这里,在堆栈上)。
顺便说一下,作为我的目标,我必须在数据库优先迁移系统中实现角色系统到项目,这段manager.AddToRole(id, role.Name);代码会在我的数据库中添加记录吗?
发布于 2016-11-17 22:12:23
下面是一个存根(未完成),显示了将新创建的用户添加到角色:
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位(这只是我使用的东西)。
https://stackoverflow.com/questions/40656705
复制相似问题