加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – Identity和自定义表之间的多对多关系. EF7 – 代码优

发布时间:2020-12-16 03:40:11 所属栏目:asp.Net 来源:网络整理
导读:如何在Identity 3.0的AspNetRoles和我的自定义表之间建立多对多的关系?我想要简单的3表,包括PermissionId和RoleId,类似于AspNetUsersRole.我有这样的事情: public class Permission{ public int PermissionId { get; set; } public string Name { get; set
如何在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)目前不支持多对多关系. ( 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; }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读