我已经将 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
,您可以按照以下步骤操作:
- 创建一个ASP.NET Web 应用程序
- 确保选择MVC并且Authentication是Individual User Accounts
转到 Models 文件夹 → 打开 IdentityModels.cs 并创建包含您要添加的自定义属性的 ApplicationRole 类:
public class ApplicationRole : IdentityRole //My custom role class { public string ApplicationId { get; set; } //My custom property }
更改
GenerateUserIdentityAsync
ApplicationUser
的方法|接受UserManager<ApplicationUser, string>
类型的参数:public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> manager) {
更改
ApplicationDbContext
基类并引入所有泛型参数:public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim> { public ApplicationDbContext() : base("DefaultConnection") {
构建项目。
- 转到 TOOLS 菜单 → Nuget 包管理器 → 单击包管理器控制台
- 输入
Enable-Migrations
然后按 Enter 并等待任务完成。 - 输入
Add-Migration "ApplicationRole"
然后按 Enter 并等待任务完成。 - 输入
Update-Database
然后按 Enter 并等待任务完成。 转到 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>()));
要管理角色,请创建
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>())); } }
转到 App_Start 文件夹 → 打开 Startup.Auth.cs 并将以下代码添加到
ConfigureAuth
方法:ConfigureAuthapp.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
现在该项目已准备好利用新的 ApplicationRole
.
关于c# - 在扩展 Roles 表后,实体类型 IdentityRole 不是当前上下文模型的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51985514/