c# - 在扩展 Roles 表后,实体类型 IdentityRole 不是当前上下文模型的一部分

标签 c# asp.net asp.net-mvc entity-framework

我已经将 Entity Framework 创建的 AspNetRoles 扩展为如下所示:

public class AspNetRoles:IdentityRole
{
        public AspNetRoles() : base() { }
        public String Label { get; set; }
        public String ApplicationId { get; set; }
        public AspNetApplications Application { get; set; }

        public static readonly String SystemAdministrator = "SystemAdministrator";
}

我知道因为我扩展了 identityrole 表,所以我必须对我的用户管理器进行更改。这就是我所做的:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

        // Configure user lockout defaults
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
        {
            MessageFormat = "Your security code is {0}"
        });
        manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        {
            Subject = "Security Code",
            BodyFormat = "Your security code is {0}"
        });
        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();
        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider = 
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}

// Configure the application sign-in manager which is used in this application.
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
    public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
        : base(userManager, authenticationManager)
    {
    }

    public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
    {
        return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
    }

    public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
    {
        return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
    }
}

public class ApplicationRoleManager : RoleManager<AspNetRoles>, IDisposable
{
    public ApplicationRoleManager(RoleStore<AspNetRoles> store) : base(store)
    { }


    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        //AppIdentityDbContext db = context.Get<AppIdentityDbContext>();
        //AppRoleManager manager = new AppRoleManager(new RoleStore<AppRole>(db));
        return new ApplicationRoleManager(new RoleStore<AspNetRoles>(context.Get<ApplicationDbContext>()));

        //return manager;
    }
}

public class ApplicationUserStore<TUser> : UserStore<TUser, AspNetRoles, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUserStore<TUser>, IUserStore<TUser, string>, IDisposable where TUser : IdentityUser
{
    public ApplicationUserStore(DbContext context) : base(context) { }
}

这是我的数据库上下文:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, AspNetRoles, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
    {
        public virtual DbSet<AspNetUsersExtendedDetails> AspNetUsersExtendedDetails { get; set; }
        public virtual DbSet<AspNetApplications> AspNetApplications { get; set; }
        public virtual DbSet<AspNetEventLogs> AspNetEventLogs { get; set; }
        public ApplicationDbContext() : base("AppStudio")
        {

        }
        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }

但是,当我启动我的应用程序时出现此错误:

实体类型 IdentityRole 不是当前上下文模型的一部分。

我不确定为什么会这样。在扩展我的角色表后,我是否遗漏了一些需要更改的内容?

最佳答案

简答

上面代码的主要问题在Create UserManager的方法| .在那个方法中,你应该创建一个 UserManager使用 UserStore它知道您创建的新角色类。为此,您可以使用 ApplicationUserStore 的实例您拥有的类或以这种方式创建新的用户存储:

new UserStore<ApplicationUser, [YourRoleClass], string, 
    IdentityUserLogin, IdentityUserRole, IdentityUserClaim(
        context.Get<ApplicationDbContext>())

如何为 IdentityRole 添加自定义属性?

将新属性添加到 IdentityRole ,您可以按照以下步骤操作:

  1. 创建一个ASP.NET Web 应用程序
  2. 确保选择MVC并且AuthenticationIndividual User Accounts
  3. 转到 Models 文件夹 → 打开 IdentityModels.cs 并创建包含您要添加的自定义属性的 ApplicationRole 类:

    public class ApplicationRole : IdentityRole   //My custom role class
    {
        public string ApplicationId { get; set; } //My custom property
    }
    
  4. 更改 GenerateUserIdentityAsync ApplicationUser的方法|接受 UserManager<ApplicationUser, string> 类型的参数:

    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> manager)
        {
    
  5. 更改 ApplicationDbContext基类并引入所有泛型参数:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
    
  6. 构建项目。

  7. 转到 TOOLS 菜单 → Nuget 包管理器 → 单击包管理器控制台
  8. 输入 Enable-Migrations然后按 Enter 并等待任务完成。
  9. 输入 Add-Migration "ApplicationRole"然后按 Enter 并等待任务完成。
  10. 输入 Update-Database然后按 Enter 并等待任务完成。
  11. 转到 App_Start 文件夹 → 打开 IdentityConfig.cs 并更改 ApplicationUserManagerUserManager<ApplicationUser, string> 派生的类并更改其 Create返回 UserManage 的方法意识到ApplicationRole :

    public class ApplicationUserManager : UserManager<ApplicationUser, string>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser, string> store)
            : base(store)
        {
        }
    
        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore<ApplicationUser, ApplicationRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>(context.Get<ApplicationDbContext>()));
    
  12. 要管理角色,请创建 ApplicationRoleManager同一文件中的类:

    public class ApplicationRoleManager : RoleManager<ApplicationRole>
    {
        public ApplicationRoleManager(IRoleStore<ApplicationRole, string> store) : base(store) { }
    
        public static ApplicationRoleManager Create(
            IdentityFactoryOptions<ApplicationRoleManager> options,
            IOwinContext context)
        {
            return new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
        }
    }
    
  13. 转到 App_Start 文件夹 → 打开 Startup.Auth.cs 并将以下代码添加到 ConfigureAuth方法:

    ConfigureAuthapp.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
    

现在该项目已准备好利用新的 ApplicationRole .

关于c# - 在扩展 Roles 表后,实体类型 IdentityRole 不是当前上下文模型的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51985514/

相关文章:

c# - Razor 是否查看解决方案文件夹?

javascript - 将值推送到 jquery 中的数组

c# - 我正在尝试在 MVC 5 中使用 Session 来传递最近注册用户的 Id

c# - 尝试在 ActionResult 中返回 HTML 会导致 HTTP 406 错误

c# - 带有 NetTcpBinding 的 WCF 服务库

c# - 如何从该类的数组中检索该类成员的数组?

javascript - 使用 XMLHttpRequest 和通用处理程序通过 FTP 下载 PDF 文件

c# - 嵌套属性的 FluentValidation 消息

C# 应用程序和 asp.NET session

c# - Kendo 网格导出到 Excel 货币格式