【问题标题】:ASP.NET MVC 5 Identity userManager.IsInRoleASP.NET MVC 5 身份 userManager.IsInRole
【发布时间】: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


    【解决方案1】:

    所以我会自己回答这个问题,以挽救我因此而遭受的数小时痛苦。

    发生这种情况的原因是我禁用了延迟加载,我已经在我的 Migrations 项目中启用了它。

    protected override void Seed(BlogContext blogContext)
        {
            AutomaticMigrationsEnabled = true;
            blogContext.Configuration.LazyLoadingEnabled = true;
            //Add seed classes here!    
        }
    

    【讨论】:

      猜你喜欢
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 2014-10-12
      • 2019-07-08
      • 2014-01-02
      • 2015-12-11
      • 2014-03-20
      • 2017-06-16
      相关资源
      最近更新 更多