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

Jia*_*nYA 4 c# asp.net asp.net-mvc 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";
}
Run Code Online (Sandbox Code Playgroud)

我知道,因为我已经扩展了identityrole表,所以必须对usermanager进行更改。这是我所做的:

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) { }
}
Run Code Online (Sandbox Code Playgroud)

这是我的DBContext:

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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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

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

Rez*_*aei 5

简短答案

上面代码中的主要问题在于的Create方法UserManager。在该方法中,您应该创建一个UserManager使用,UserStore它可以识别您创建的新角色类。为此,您可以使用拥有的ApplicationUserStore类的实例,或通过以下方式创建新的用户存储:

new UserStore<ApplicationUser, [YourRoleClass], string, 
    IdentityUserLogin, IdentityUserRole, IdentityUserClaim(
        context.Get<ApplicationDbContext>())
Run Code Online (Sandbox Code Playgroud)

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

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

  1. 创建一个ASP.NET Web应用程序
  2. 确保选择“ MVC”,并且“ 身份验证”是“ 个人用户帐户”
  3. 转到模型文件夹?打开IdentityModels.cs并创建包含要添加的自定义属性的ApplicationRole类:

    public class ApplicationRole : IdentityRole   //My custom role class
    {
        public string ApplicationId { get; set; } //My custom property
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 更改类型为的参数的接受GenerateUserIdentityAsync方法:ApplicationUserUserManager<ApplicationUser, string>

    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> manager)
        {
    
    Run Code Online (Sandbox Code Playgroud)
  5. 更改ApplicationDbContext基类并引入所有通用参数:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
    
    Run Code Online (Sandbox Code Playgroud)
  6. 生成项目。

  7. 转到“ 工具”菜单?Nuget软件包管理器?单击程序包管理器控制台
  8. 键入Enable-Migrations并按Enter,直到任务完成。
  9. 键入Add-Migration "ApplicationRole"并按Enter,直到任务完成。
  10. 键入Update-Database并按Enter,直到任务完成。
  11. 转到App_Start文件夹?打开IdentityConfig.cs并更改ApplicationUserManager要从UserManager<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>()));
    
    Run Code Online (Sandbox Code Playgroud)
  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>()));
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  13. 转到App_Start文件夹?打开Startup.Auth.cs并将以下代码添加到ConfigureAuth方法中:

    ConfigureAuthapp.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
    
    Run Code Online (Sandbox Code Playgroud)

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

  • @El7or 不客气,感谢您的反馈。如果您还要自定义身份用户,您可能需要查看[这篇文章](/sf/answers/2840555861/)。 (2认同)