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



如何在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. 

EF Core(EF7)当前不支持没有联接实体的多对多关系。(参考)

因此,您应该为联接表创建一个实体类,并映射两个单独的一对多关系。喜欢

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

关于这个问题的答案,可以像这样更容易地完成-

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

要导航,请使用Select:

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

添加此命名空间-

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

就是这样,Happy编码:)

相关内容

  • 没有找到相关文章

最新更新