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

时间:2018-08-23 12:09:53

标签: 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";
}

我了解到,因为我已经扩展了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) { }
}

这是我的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();
        }
    }

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

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

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

1 个答案:

答案 0 :(得分:5)

简短答案

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

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

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

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

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

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

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

    ApplicationDbContext
  6. 构建项目。

  7. 转到工具菜单→ Nuget Package Manager →单击 Package Manager控制台
  8. 键入public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim> { public ApplicationDbContext() : base("DefaultConnection") { ,然后按 Enter 并等待任务完成。
  9. 键入Enable-Migrations,然后按 Enter 并等待任务完成。
  10. 键入Add-Migration "ApplicationRole",然后按 Enter 并等待任务完成。
  11. 转到 App_Start 文件夹→打开 IdentityConfig.cs 并更改Update-Database类以从ApplicationUserManager派生,并更改其类别UserManager<ApplicationUser, string>方法返回Create知道UserManage的方法:

    ApplicationRole
  12. 要管理角色,请在同一文件中创建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>())); 类:

    ApplicationRoleManager
  13. 转到 App_Start 文件夹→打开 Startup.Auth.cs 并将以下代码添加到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>())); } } 方法中:

    ConfigureAuth

现在该项目已准备好利用新的ConfigureAuthapp.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);