自定义ASP.NET核心标识表

时间:2018-03-25 01:46:50

标签: asp.net asp.net-core asp.net-identity asp.net-core-2.0 ef-migrations

当man在asp.net core 2中自定义Identity类时,表之间的关系不会自动创建。

如何以最简单的方式创建表之间的关系?

用户类:

public class User : IdentityUser<int>
{
    // codes
}

角色等级:

public class Role : IdentityRole<int>
{
    public Role() : base()
    {

    }
    public Role(string roleName) : base(roleName)
    {

    }
}

RoleClaim类:

public class RoleClaim : IdentityRoleClaim<int> { }

UserClaim类:

public class UserClaim : IdentityUserClaim<int> { }

UserLogin类:

public class UserLogin : IdentityUserLogin<int> { }

UserRole类:

public class UserRole : IdentityUserRole<int> { }

UserToken类:

public class UserToken : IdentityUserToken<int> { }

custom Identity without relations between tables

我希望我的表之间的关系相同:

Default Identity Table

2 个答案:

答案 0 :(得分:4)

我通过在UserRoleUserClaimUserRoleUserLogin,{{1}中编写一些代码来定义表的关系}和RoleClaim类以及UserToken类。

角色等级:

ApplicationDbContext

RoleClaim类:

public class Role : IdentityRole<int>
{
    public Role() : base()
    {

    }
    public Role(string roleName) : this()
    {
        Name = roleName;
    }

    public virtual ICollection<UserRole> Users { get; set; }
    public virtual ICollection<RoleClaim> Claims { get; set; }
}

用户类:

public class RoleClaim : IdentityRoleClaim<int>
{
    public virtual Role Role { get; set; }
}

UserClaim类:

public class User : IdentityUser<int>
{
    public virtual ICollection<UserToken> UserTokens { get; set; }

    public virtual ICollection<UserRole> Roles { get; set; }

    public virtual ICollection<UserLogin> Logins { get; set; }

    public virtual ICollection<UserClaim> Claims { get; set; }
}

UserLogin类:

public class UserClaim : IdentityUserClaim<int>
{
    public virtual User User { get; set; }
}

UserRole类:

public class UserLogin : IdentityUserLogin<int>
{
    public virtual User User { get; set; }
}

UserToken类:

public class UserRole : IdentityUserRole<int>
{
    public virtual User User { get; set; }
    public virtual Role Role { get; set; }
}

ApplicationDbContext类:

public class UserToken : IdentityUserToken<int>
{
    public virtual User User { get; set; }
}

您可以在此图片中看到结果: CustomIdentityTables

答案 1 :(得分:0)

IdentityDbContext存在泛型类型重载。如果您要自定义某些类,则必须通过这些重载告诉Identity实际使用哪些实体。因为,你几乎都在定制所有东西,你需要最广泛的过载:

public class MyContext : IdentityDbContext<User, CustomRole, int, CustomUserClaim, CustomUserRole, CustomUserLogin, CustomRoleClaim, CustomUserLogin>