ASP.NET MVC 5 Identity userManager.IsInRole

2019-02-18 13:46发布

问题:

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!

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? 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.

    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();
    }

回答1:

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!    
    }