[英]ASP.NET MVC 5 Identity userManager.IsInRole
The following code does not work, and I can't explain why... My user manager is causing significant distress in that it creates users and roles just fine but when I run this code userManager.IsInRole is always returning false, so the second time I run my seed I am hitting errors because it is trying to create the record despite the fact it already exists! 以下代码不起作用,我无法解释为什么...我的用户管理器造成了很大的困扰,因为它创建用户和角色就好了但是当我运行此代码时userManager.IsInRole总是返回false,所以第二个时间我运行我的种子我遇到了错误,因为它试图创建记录,尽管它已经存在!
Please note that this is occurring when I am running update-database against my migrations project, is the fact this is a non ASP project causing issues, if so why? 请注意,这是在我针对迁移项目运行update-database时发生的,事实上这是一个导致问题的非ASP项目,如果是这样,为什么呢? shouldn't an error be thrown. 不应该抛出错误。
This is the first project I have used Identity and although when it works it seems good, there is very little up to date good quality documentation available, so if anyone has any sources for this I would be grateful. 这是我使用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();
}
So I will answer this myself to save anyone the hours of pain I suffered because of this. 因此,我将自己回答这个问题,以拯救任何人因此而遭受的痛苦。
The reason for this occurring was that I had lazy loading disabled, I have enabled this to be on in my Migrations project like so. 出现这种情况的原因是我禁用了延迟加载,我已经在我的迁移项目中启用了这个,就像这样。
protected override void Seed(BlogContext blogContext)
{
AutomaticMigrationsEnabled = true;
blogContext.Configuration.LazyLoadingEnabled = true;
//Add seed classes here!
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.