How to implement a relationship between IdentityRo

2019-08-12 13:16发布

问题:

I'm working with a project similar to the MVC template project.

I've created some models that I want to be represented in the database. I can create them with a DbContext class just fine, the issue is connecting my class's RoleId with ASP.Net Identity's Role table's id.

Any ideas as to how this is possible?

回答1:

Let's say that RoleDependent is your entity class. Then:

1) If you need one-to-many (1:N) relationship beetween RoleDependent and Role:

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

that will result in the following migration:

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) If you need one-to-one (1:1) relationship beetween RoleDependent and Role:

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

which would result in the migration:

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);