如何实现 IdentityRole (dbo.AspNetRoles) 和自定义实体之间的关系?

How to implement a relationship between IdentityRole (dbo.AspNetRoles) and a custom entity?

我正在处理一个类似于 MVC 模板项目的项目。

我已经创建了一些我想要在数据库中表示的模型。我可以用 DbContext class 创建它们就好了,问题是将我的 class 的 RoleId 与 ASP.Net 身份的角色 table 的 id 连接起来。

关于这如何可能的任何想法?

假设 RoleDependent 是您的实体 class。那么:

1) 如果您需要 RoleDependentRole 之间的一对多 (1:N) 关系

public class RoleDependent
{
    public Int32 Id { get; set; }
    public virtual IdentityRole IdentityRole { get; set; }
}

这将导致以下迁移:

CreateTable("dbo.RoleDependents",
c => new
    {
        Id = c.Int(nullable: false, identity: true),
        IdentityRole_Id = c.String(maxLength: 128),
    })
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetRoles", t => t.IdentityRole_Id)
.Index(t => t.IdentityRole_Id);

2) 如果您需要 RoleDependentRole 之间的一对一 (1:1) 关系

public class RoleDependent
{
    public String Id { get; set; }
    [ForeignKey("Id")]
    public virtual IdentityRole IdentityRole { get; set; }
}

这将导致迁移:

CreateTable("dbo.RoleDependents",
    c => new
        {
            Id = c.String(nullable: false, maxLength: 128),
        })
    .PrimaryKey(t => t.Id)
    .ForeignKey("dbo.AspNetRoles", t => t.Id)
    .Index(t => t.Id);