我想在不同的控制器(非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
上下文类中是否有public class ApplicationDbContext : IdentityDbContext<ApplicationUser>{}
? - Mike Debelavar userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create()));
翻译:创建一个新的UserManager<ApplicationUser>
对象,并传入UserStore<ApplicationUser>(ApplicationDbContext.Create())
作为参数。 - Mike Debela