【发布时间】:2015-05-31 07:16:16
【问题描述】:
我正在尝试从不同的控制器(不是accountcontroller)设置aspnetuser 表中列的值。我一直在尝试访问UserManager,但我不知道该怎么做。
到目前为止,我已经在要使用的控制器中尝试了以下操作:
ApplicationUser u = UserManager.FindById(User.Identity.GetUserId());
u.IsRegComplete = true;
UserManager.Update(u);
这不会编译(我认为是因为UserManager 还没有被实例化控制器)
我还尝试在AccountController 中创建一个公共方法来接受我想要将值更改为的值并在那里执行,但我不知道如何调用它。
public void setIsRegComplete(Boolean setValue)
{
ApplicationUser u = UserManager.FindById(User.Identity.GetUserId());
u.IsRegComplete = setValue;
UserManager.Update(u);
return;
}
您如何在帐户控制器之外访问和编辑用户数据?
更新:
我尝试像这样在另一个控制器中实例化 UserManager:
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
ApplicationUser u = userManager.FindById(User.Identity.GetUserId());
我的项目完成了(有点兴奋),但是当我运行代码时,我收到以下错误:
Additional information: The entity type ApplicationUser is not part of the model for the current context.
更新 2:
我已将函数移至 IdentityModel(不要问我在这里抓着稻草),如下所示:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public Boolean IsRegComplete { get; set; }
public void SetIsRegComplete(string userId, Boolean valueToSet)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());
ApplicationUser u = new ApplicationUser();
u = userManager.FindById(userId);
u.IsRegComplete = valueToSet;
return;
}
}
但是我仍然得到以下信息:
The entity type ApplicationUser is not part of the model for the current context.
IdentitiesModels.cs中还有如下类:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
我在这里做错了什么?感觉就像我完全在吠叫错误的树。我要做的就是从不同控制器(即不是 AccountsController)的操作中更新 aspnetuser 表中的列。
【问题讨论】:
-
从错误消息看来,您传递给商店的“db”与包含您的身份表的 DbContext 不同。
-
你的
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>{}上下文类中有public class ApplicationDbContext : IdentityDbContext<ApplicationUser>{}吗? -
查看上面的更新帖子 - 谢谢
-
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create())); -
是的,这很奏效。谢谢!
标签: asp.net-mvc asp.net-mvc-5 asp.net-identity-2 actioncontroller