使用自定义标识用户时,用户角色表上的额外列(ASP.NET 5.2EF 6和标识2)

时间:2016-11-09 14:37:32

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

我为我的MVC应用程序使用了基于4层的架构:域,数据,服务和MVC。 在我的域层中,我创建了一个继承自IdentityUser的Employee类。它包含自定义属性和我从MVC中的身份模式中的应用程序用户类获得的GenerateUserIdentityAsync方法。

public class Employee : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<Employee> 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;
    }
    public String CIN { get; set; }
    public String FirstName { get; set; }

在我的数据层中,我创建了一个继承自IdentityDbContext的上下文。我没有在我的dbset中提到员工。我还增加了许多关于我的申请,特别是员工类。

public class MyCWCContexte : IdentityDbContext<Employee>
{
    public MyCWCContexte()
        : base("name=CWCDB")
    {

    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

我所做的最后一项改变是我已经更改了StartUp.Auth.cs和IdentityConfig文件,因此它们与我的Employee类和我的上下文匹配。

 public class ApplicationUserManager : UserManager<CWC.Domain.Entities.Employee>
{
    public ApplicationUserManager(IUserStore<CWC.Domain.Entities.Employee> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    {
        var manager = new ApplicationUserManager(new UserStore<CWC.Domain.Entities.Employee>(context.Get<MyCWCContexte>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<CWC.Domain.Entities.Employee>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

从迁移生成数据库进展顺利,问题出在aspnet自动生成的表中,例如来自IdentityUserRole类。在尝试添加用户并向其添加角色时,我发现aspnetuserroles包含3列,如下所示:

Screenshot of select * from aspnetuserroles UserId和RoleId是表的PK,Employee_Id是Employee的FK。我认为UserId应该是Fk而不是。 这是一个真正的问题,因为授权注释和来自用户管理器的GetRoles例如不能正常工作。 UserManager.GetRoles(Employee.Id)总是返回null,而我得到的Employee.Id具有我从数据库获得的正确值。 我认为这是因为comparaison是在employee_id而不是userid上进行的。 你对此有所了解吗?我是ASP.NET的初学者。提前谢谢。

1 个答案:

答案 0 :(得分:0)

通过从DbContext:IdentityDbContext中删除通用性(Employee)来纠正它 我现在的背景是: 公共类MyCWCContexte:IdentityDbContext

相关问题