扩展ASP.NET标识角色:IdentityRole不是当前上下文模型的一部分

时间:2014-03-03 08:09:46

标签: c# asp.net-mvc asp.net-mvc-5 asp.net-identity

我正在尝试在我的MVC5应用程序中使用新的ASP.NET标识,特别是我正在尝试将ASP.NET标识集成到现有数据库中。我已经阅读了有关DB First和ASP.NET Identity的问题/答案,并且已经遵循了所有建议,我仍然无法将角色添加到我的数据库,尽管添加用户没有问题。这是我的代码:

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': The entity type IdentityRole is not part of the model for the current context.

的异常

这是我的背景:

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; }
......
}

我的AspNetUserAspNetRole类分别来自IdentityUserIdentityRole,但我仍然得到了这个例外。这是我的数据库图表:

enter image description here

非常感谢任何帮助。

6 个答案:

答案 0 :(得分:8)

您必须在创建User Store期间指定使用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, AspNetRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim> 
{
}

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

    public UserStore<AspNetUser, AspNetRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim> UserStore
    {
        get 
        {                
            return new UserStore<AspNetUser, AspNetRole, string, IdentityUserLogin, IdentityUserRole, 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);
        }
    }
}

答案 1 :(得分:4)

在尝试以干净的方式工作几天之后,我得出的结论是,如果您首先使用数据库并希望将ASP.NET身份集成到您的应用程序中,那么到目前为止最简单最干净的解决方案是通过覆盖ASP.NET标识来创建自己的成员资格提供程序。这实际上非常简单,到目前为止,我已根据自己的喜好实施了UserStoreRoleStore。我在我的数据库中添加了特定于我的域的列/关系,每当我创建用户或角色时,我通过添加所需的关系来处理我的数据库提交。我的UserStore实施与this非常相似。我的RoleStore实现是这样的:

public class ApplicationRoleStore : IRoleStore<ApplicationRoleDTO>
{
    private PayrollDBEntities _context;
    public ApplicationRoleStore() { }

    public ApplicationRoleStore(PayrollDBEntities database)
    {
        _context = database;
    }

    public Task CreateAsync(ApplicationRoleDTO role)
    {
        if (role == null)
        {
            throw new ArgumentNullException("RoleIsRequired");
        }
        var roleEntity = ConvertApplicationRoleDTOToAspNetRole(role);
        _context.AspNetRoles.Add(roleEntity);
        return _context.SaveChangesAsync();

    }

    public Task DeleteAsync(ApplicationRoleDTO role)
    {
        var roleEntity = _context.AspNetRoles.FirstOrDefault(x => x.Id == role.Id);
        if (roleEntity == null) throw new InvalidOperationException("No such role exists!");
        _context.AspNetRoles.Remove(roleEntity);
        return _context.SaveChangesAsync();
    }

    public Task<ApplicationRoleDTO> FindByIdAsync(string roleId)
    {
        var role = _context.AspNetRoles.FirstOrDefault(x => x.Id == roleId);

        var result = role == null
            ? null
            : ConvertAspNetRoleToApplicationRoleDTO(role);

        return Task.FromResult(result);
    }

    public Task<ApplicationRoleDTO> FindByNameAsync(string roleName)
    {

        var role = _context.AspNetRoles.FirstOrDefault(x => x.Name == roleName);

        var result = role == null
            ? null
            : ConvertAspNetRoleToApplicationRoleDTO(role);

        return Task.FromResult(result);
    }

    public Task UpdateAsync(ApplicationRoleDTO role)
    {

        return _context.SaveChangesAsync();
    }

    public void Dispose()
    {
        _context.Dispose();
    }
    private ApplicationRoleDTO ConvertAspNetRoleToApplicationRoleDTO(AspNetRole aspRole)
    {
        return new ApplicationRoleDTO{
            Id = aspRole.Id,
            EnterpriseId = aspRole.EnterpriseId,
            Name = aspRole.Name
        };
    }

    private AspNetRole ConvertApplicationRoleDTOToAspNetRole(ApplicationRoleDTO appRole)
    {
        return new AspNetRole{
            Id = appRole.Id,
            EnterpriseId = appRole.EnterpriseId,
            Name = appRole.Name,
        };
    }
}

我的ApplicationRoleDTO:

public class ApplicationRoleDTO : IRole
{
    public ApplicationRoleDTO()
    {
        Id = Guid.NewGuid().ToString();
    }

    public ApplicationRoleDTO(string roleName)
        : this()
    {
        Name = roleName;
    }
    public string Id { get; set; }
    public string Name { get; set; }
    public Guid EnterpriseId { get; set; }
}

我还发现这两篇文章很有帮助:

Overview of Custom Storage Providers for ASP.NET Identity

Implementing a Custom MySQL ASP.NET Identity Storage Provider

答案 2 :(得分:2)

我将在这里用代码示例解释:)。

诀窍是,它们已经在IdentityDbContext中(AspNetRoles,AspNetUserClaims,AspNetUsers,....)

在IdentityModel中,您将看到顶部的ApplicationUser为空。如果要自定义这些用户或角色,只需在此处添加属性,然后通过控制台更新数据库

我的上下文示例

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<Request> Requests { get; set; }
    public DbSet<Reservation> Reservations { get; set; }
    public DbSet<PriceType> PriceTypes { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<Price> Prices { get; set; }
    public DbSet<GuestbookPost> Posts { get; set; }
    public DbSet<Count> Counts { get; set; }
    public DbSet<Invoice> Invoices { get; set; }
    public DbSet<InvoiceLine> InvoiceLines { get; set; }

    ...

}

所以这里没有定义应用程序用户,但我确实为它添加了更多属性,例如:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string GroupName { get; set; }
    public string Email { get; set; }
    [StringLength(15)]
    public string Phone { get; set; }
    public string Remark { get; set; }
    public DateTime? BirthDate { get; set; }
    public DateTime ValidFrom { get; set; }
    public DateTime ValidUntil { get; set; }

    public string Street { get; set; }
    public string ZipCode { get; set; }
    public string City { get; set; }

    public virtual ICollection<Request> Requests { get; set; } 
}

答案 3 :(得分:1)

我知道这是一个老问题,但是万一其他人在修改asp身份以使用数字主键(int / long)而不是Identity Roles的默认字符串时很难添加角色/用户,所以如果你已经将IdentityModels.cs中的IdentityUserRole更改为:

public class Role : IdentityRole<long, UserRole>
{
    public Role() { }
    public Role(string name) { Name = name; }
}

在构造RoleManager时,您必须使用类Role而不是默认的IdentityRole,因此您的代码应如下所示:

public static void RegisterUserRoles()
{
     ApplicationDbContext context = new ApplicationDbContext();

     var RoleManager = new RoleManager<Role, long>(new RoleStore(context));

     if (!RoleManager.RoleExists("Administrador"))
     {
         var adminRole = new Role {
              Name = "Administrador",
         };
         RoleManager.Create(adminRole);
     }
}

所以这应该正确地填充你的数据库,我认为所有经验丰富的ASP程序员已经知道这一点,但对于其他人来说,这可能需要一些时间来弄明白。

答案 4 :(得分:0)

我用另一种方式解决了。 首先,我分为两个不同的项目和上下文。 我处理身份的项目具有以下上下文:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDisposable
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

这是我的ApplicationUser:

public class ApplicationUser : IdentityUser
    {
        //Put here the extra properties that Identity does not handle
        [Required]
        [MaxLength(150)]
        public string Nome { get; set; }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

我的ApplicationUserManager看起来像这样:

public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {
            //Setting validator to user name
            UserValidator = new UserValidator<ApplicationUser>(this)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            //Validation Logic and Password complexity 
            PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = false,
                RequireDigit = false,
                RequireLowercase = false,
                RequireUppercase = false,
            };

            //Lockout
            UserLockoutEnabledByDefault = true;
            DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            MaxFailedAccessAttemptsBeforeLockout = 5;

            // Providers de Two Factor Autentication
            RegisterTwoFactorProvider("Código via SMS", new PhoneNumberTokenProvider<ApplicationUser>
            {
                MessageFormat = "Seu código de segurança é: {0}"
            });

            RegisterTwoFactorProvider("Código via E-mail", new EmailTokenProvider<ApplicationUser>
            {
                Subject = "Código de Segurança",
                BodyFormat = "Seu código de segurança é: {0}"
            });

            //Email service
            EmailService = new EmailService();

            // Definindo a classe de serviço de SMS
            SmsService = new SmsService();

            var provider = new DpapiDataProtectionProvider("Braian");
            var dataProtector = provider.Create("ASP.NET Identity");

            UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtector);

        }
    }

我希望这对某人有帮助。 此解决方案来自本文: Eduardo Pires - But it is in Portuguese

答案 5 :(得分:-2)

我通过更改web.config DefaultConnection connectionString属性来解决此问题,因此它指向新的SQLServer数据库