微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 扩展ASP.NET身份角色:IdentityRole不是当前上下文模型的一部分

我试图在我的MVC5应用程序中使用新的ASP.NET身份,具体来说我正在将ASP.NET Identity集成到现有的数据库中.我已经阅读了关于DB First和ASP.NET Identity的SO的问题/答案,并遵循所有建议,我仍然不能添加角色到我的数据库,虽然我没有添加用户的问题.这是我的代码
var context = new PayrollDBEntities();
var roleManager = new RoleManager<AspNetRole>(new RoleStore<AspNetRole>(context));

bool roleExists = roleManager.RoleExists(roleDto.Name);
if (roleExists){
    return false;
}

var role = new AspNetRole(roleDto.Name){
    Name = roleDto.Name,};

IdentityResult result = roleManager.Create(role);//Getting exception here

代码的最后一行,我收到类型“system.invalidOperationException”的异常:实体类型IdentityRole不是当前上下文模型的一部分.

这是我的上下文:

public partial class PayrollDBEntities : IdentityDbContext
{
        public PayrollDBEntities()
            : base("name=PayrollDBEntities")
        {
        }

        public virtual DbSet<AspNetRole> AspNetRoles { get; set; }
        public virtual DbSet<AspNetUserClaim> AspNetUserClaims { get; set; }
        public virtual DbSet<AspNetUserLogin> AspNetUserLogins { get; set; }
        public virtual DbSet<AspNetUser> AspNetUsers { get; set; }
......
}

我的AspNetUser和AspNetRole类派生自IdentityUser和IdentityRole,但是我仍然得到这个异常.这是我的数据库图:

任何帮助将不胜感激.

解决方法

您必须在创建用户商店期间指定使用AspNetRole而不是IdentityRole.您可以使用具有6种类型参数的UserStore类来实现此目的:
new UserStore<AspNetUser,AspNetRole,string,IdentityUserLogin,IdentityUserRole,IdentityUserClaim>(new PayrollDBEntities());

这也表示用户管理器创建时的更改.以下是有关创建所需实例的简化示例:

public class AspNetUser : IdentityUser { /*customization*/ }

public class AspNetRole : IdentityRole { /*customization*/ }

public class PayrollDBEntities : IdentityDbContext //or : IdentityDbContext <AspNetUser,IdentityUserClaim> 
{
}

public class Factory 
{
    public IdentityDbContext DbContext 
    { 
        get 
        {
            return new PayrollDBEntities();
        } 
    }

    public UserStore<AspNetUser,IdentityUserClaim> UserStore
    {
        get 
        {                
            return new UserStore<AspNetUser,IdentityUserClaim>(DbContext);
        }
    }

    public UserManager<AspNetUser,string> UserManager
    { 
        get 
        {
            return new UserManager<AspNetUser,string>(UserStore);
        } 
    }

    public RoleStore<AspNetRole> RoleStore 
    {
        get 
        {
            return new RoleStore<AspNetRole>(DbContext);
        }
    }

    public RoleManager<AspNetRole> RoleManager 
    {
        get 
        {
            return new RoleManager<AspNetRole>(RoleStore);
        }
    }
}

原文地址:https://www.jb51.cc/csharp/95220.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐