gpt4 book ai didi

asp.net - 身份和自定义表之间的多对多关系。 EF7-代码优先

转载 作者:行者123 更新时间:2023-12-04 16:42:40 25 4
gpt4 key购买 nike

如何在Identity 3.0的AspNetRoles和自定义表之间建立多对多关系?我想要带有PermissionId和RoleId的简单3表,类似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核心(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; }
}

关于asp.net - 身份和自定义表之间的多对多关系。 EF7-代码优先,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38438052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com