Identity和自定义表之间的多对多关系。 EF7 - 代码优先

时间:2016-07-18 13:30:51

标签: asp.net asp.net-mvc entity-framework asp.net-identity

如何在Identity 3.0的AspNetRoles和我的自定义表之间建立多对多的关系?我想要简单的3表,包括PermissionId和RoleId,类似于AspNetUsersRole。我有这样的事情:

public class Permission
{
    public int PermissionId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<ApplicationRole> Roles { get; set; }
}

public class ApplicationRole : IdentityRole
{
    public virtual ICollection<Permission> Permissions { get; set; }
}

但是当我想添加迁移时,我收到了错误:

 Unable to determine the relationship represented by navigation property 'ApplicationRole.Permissions' of type 'ICollection<Permission>'. Either manually configure the relationship, or ignore this property from the model. 

3 个答案:

答案 0 :(得分:10)

EF Core (EF7)目前不支持多对多关系没有加入实体。 (Reference

因此,您应该做的是为连接表创建一个实体类,并映射两个单独的一对多关系。等;

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<PostTag>()
        .HasKey(t => new { t.PostId, t.TagId });

    modelBuilder.Entity<PostTag>()
        .HasOne(pt => pt.Post)
        .WithMany(p => p.PostTags)
        .HasForeignKey(pt => pt.PostId);

    modelBuilder.Entity<PostTag>()
        .HasOne(pt => pt.Tag)
        .WithMany(t => t.PostTags)
        .HasForeignKey(pt => pt.TagId);
}

public class PostTag
{
        public int PostId { get; set; }
        public Post Post { get; set; }

        public string TagId { get; set; }
        public Tag Tag { get; set; }
}

答案 1 :(得分:3)

关于this question answer,可以更容易地做到这一点 -

class Photo
{
    public int Id { get; set; }
    public ICollection<PersonPhoto> PersonPhotos{ get; set; }
}

class PersonPhoto
{
    public int PhotoId { get; set; }
    public Photo Photo { get; set; }

    public int PersonId { get; set; }
    public Person Person { get; set; }
}

class Person
{
    public int Id { get; set; }
    public ICollection<PersonPhoto> PersonPhotos{ get; set; }
}

请务必使用复合键配置PersonPhoto

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<PersonPhoto>().HasKey(x => new { x.PhotoId, x.PersonId });
}

要导航,请使用选择:

// person.Photos
var photos = person.PersonPhotos.Select(c => c.Photo);

答案 2 :(得分:1)

添加此命名空间-

using Microsoft.AspNetCore.Identity;


public class Permission
{
     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
     public int PermissionId { get; set; }
     public string Name { get; set; }
     public string UserIdFK { get; set; } //Foreign Key of Identity tbl

     [ForeignKey("UserIdFK")]
     public IdentityUser UserDetail { get; set; }
}

就这样,快乐的编码:)