实体类型 IdentityRole 不是当前上下文 Asp.net mvc 模型的一部分
Posted
技术标签:
【中文标题】实体类型 IdentityRole 不是当前上下文 Asp.net mvc 模型的一部分【英文标题】:The entity type IdentityRole is not part of the model for the current context Asp.net mvc 【发布时间】:2017-06-01 01:45:46 【问题描述】:我是 MVC 的新手。我正在创建角色管理器。到目前为止,我已经在 web.config 中为管理员用户添加了凭据。
我尝试将数据类型字符串更改为整数并通过添加所需位置来更新代码。到目前为止,我在构建项目时没有看到任何错误。当我运行我的网站时,出现上述错误。 附加信息:实体类型 IdentityRole 不是当前上下文模型的一部分。
这是我的代码。
private void CreateAdminIfNeeded()
// Get Admin Account
string AdminUserName = ConfigurationManager.AppSettings["AdminUserName"];
string AdminPassword = ConfigurationManager.AppSettings["AdminPassword"];
string fileName = HttpContext.Server.MapPath(@"~/Images/noImg.png");
byte[] imageData = null;
FileInfo fileInfo = new FileInfo(fileName);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imageData = br.ReadBytes((int)imageFileLength);
// See if Admin exists
var objAdminUser = UserManager.FindByEmail(AdminUserName);
if (objAdminUser == null)
//See if the Admin role exists. In this part I am getting error
if (!RoleManager.RoleExists("Administrator"))
// Create the Admin Role (if needed)
IdentityRole objAdminRole = new IdentityRole("Administrator");
RoleManager.Create(objAdminRole);
// Create Admin user
var objNewAdminUser = new ApplicationUser UserName = AdminUserName, Email = AdminUserName, UserPhoto = imageData ;
var AdminUserCreateResult = UserManager.Create(objNewAdminUser, AdminPassword);
// Put user in Admin role
UserManager.AddToRole(objNewAdminUser.Id, "Administrator");
#endregion
我在这部分出现错误。
//See if the Admin role exists.
if (!RoleManager.RoleExists("Administrator"))
// Create the Admin Role (if needed)
IdentityRole objAdminRole = new
身份模型代码:
命名空间 SoftechGoSMS.Models 公共类 ApplicationUser : IdentityUser 公共字节 [] 用户照片 获取;放;
public string DomainName get; set;
public string CompanyName get; set;
public string CopyrightInformation get; set;
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
public class CustomUserRole : IdentityUserRole<int>
public class CustomUserClaim : IdentityUserClaim<int>
public class CustomUserLogin : IdentityUserLogin<int>
public class CustomRole : IdentityRole<int, CustomUserRole>
public CustomRole()
public CustomRole(string name) Name = name;
public class CustomUserStore : UserStore<ApplicationUser, CustomRole, int,
CustomUserLogin, CustomUserRole, CustomUserClaim>
public CustomUserStore(ApplicationDbContext context)
: base(context)
public class CustomRoleStore : RoleStore<CustomRole, int, CustomUserRole>
public CustomRoleStore(ApplicationDbContext context)
: base(context)
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole,
int, CustomUserLogin, CustomUserRole, CustomUserClaim>
public ApplicationDbContext()
: base("SMSGoConnection")
public static ApplicationDbContext Create()
return new ApplicationDbContext();
#region public ApplicationRoleManager RoleManager
public ApplicationRoleManager RoleManager
get
return _roleManager ??
HttpContext.GetOwinContext()
.GetUserManager<ApplicationRoleManager>();
private set
_roleManager = value;
应用程序角色管理器代码:
public class ApplicationRoleManager : RoleManager<IdentityRole>
public ApplicationRoleManager(IRoleStore<IdentityRole, string> store)
: base(store)
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
var roleStore = new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>());
return new ApplicationRoleManager(roleStore);
启动验证码:
public partial class Startup
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Add Role Manager
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
getUserIdCallback: id => id.GetUserId<int>())
);
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
【问题讨论】:
显示你的身份模型。 @UmairAnwaar 请使用身份模型检查更新的问题 使用 CustomRole() 代替 IdentityRole 创建角色。 请出示您的角色管理器初始化。 @UmairAnwaar 请检查更新的问题 【参考方案1】:当您实现自定义角色以将 id 从字符串转换为 int 时,您应该使用 CustomRole 来创建新角色
//See if the Admin role exists. In this part I am getting error
if (!RoleManager.RoleExists("Administrator"))
// Create the Admin Role Using CustomRole not IdenitityRole
CustomRole objAdminRole = new CustomRole("Administrator");
RoleManager.Create(objAdminRole);
像这样修改你的 ApplicationRoleManager
public class ApplicationRoleManager : RoleManager<CustomRole, int>
public ApplicationRoleManager(IRoleStore<CustomRole, int> roleStore)
: base(roleStore)
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
return new ApplicationRoleManager(new CustomRoleStore(context.Get<ApplicationDbContext>()));
【讨论】:
我已在问题中添加。请检查 非常感谢。错误消失了。现在,出现了新的错误。附加信息:从具体化的“System.String”类型到“System.Int32”类型的指定转换无效。此错误在此行中引发。 if (!RoleManager.RoleExists("Administrator")) 我试图将用户 ID 的字符串更改为 int。当我签入数据库时,未设置自动增量。出于这个原因,我收到这样的错误。我无法注册新用户。这是错误。无法将值 NULL 插入到列“Id”、表“SMSGo.dbo.AspNetUsers”中;列不允许空值。插入失败。声明已终止。 我在 if (!RoleManager.RoleExists("Administrator")) 附近收到此错误。从具体化的“System.String”类型到“System.Int32”类型的指定转换无效。 请检查更新的问题。这是我在单击登录按钮时遇到的错误。附近 if (!RoleManager.RoleExists("Administrator")) 。从具体化的“System.String”类型到“System.Int32”类型的指定转换无效。以上是关于实体类型 IdentityRole 不是当前上下文 Asp.net mvc 模型的一部分的主要内容,如果未能解决你的问题,请参考以下文章
实体类型 ApplicationUser 不是当前上下文模型的一部分