【发布时间】:2014-04-30 09:58:11
【问题描述】:
以下代码不起作用,我无法解释为什么...我的用户管理器造成了很大的困扰,因为它可以很好地创建用户和角色,但是当我运行此代码时 userManager.IsInRole 总是返回 false,所以我第二次运行我的种子时遇到了错误,因为它试图创建记录,尽管它已经存在!
请注意,当我针对我的迁移项目运行更新数据库时,会发生这种情况,这是一个非 ASP 项目导致问题的事实,如果是,为什么?不应该抛出错误。
这是我使用 Identity 的第一个项目,虽然它看起来不错,但几乎没有最新的高质量文档可用,所以如果有人有这方面的任何资源,我将不胜感激。
public void Run(BlogContext blogContext)
{
var userStore = new UserStore<User>((BlogContext) blogContext);
var userManager = new UserManager<User>(userStore);
var userRoles = new List<UserRole>()
{
new UserRole() {Username = "SysAdmin@test.com", Role = "SysAdmin"},
new UserRole() {Username = "testAdmin@test.com", Role = "Admin"},
new UserRole() {Username = "testAuthor@test.com", Role = "Author"}
};
foreach (var userRole in userRoles)
{
var userId = userManager.FindByName(userRole.Username).Id;
if (!userManager.IsInRole(userId, userRole.Role))
userManager.AddToRole(userId, userRole.Role);
}
blogContext.SaveChanges();
}
【问题讨论】:
标签: c# asp.net asp.net-mvc entity-framework-migrations asp.net-identity