本文介绍了身份和自定义表之间的多对多关系. EF7-代码优先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Identity 3.0的AspNetRoles和自定义表之间建立多对多关系?我想要带有PermissionId和RoleId的简单3表,类似AspNetUsersRole.我有这样的东西:
How can I make many to many relation between AspNetRoles from Identity 3.0 and my custom table? I want simple 3 table, with both PermissionId and RoleId, something like AspNetUsersRole. I have something like this:
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; }
}
但是当我想添加迁移时,出现错误:
But when I want to add migration, I got error:
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)当前不支持没有联接实体的多对多关系. (参考)
EF Core (EF7) does not currently support many to many relationship without a join entity. (Reference)
因此,您应该做的是为联接表创建一个实体类,并映射两个单独的一对多关系.喜欢;
So, what you should do is to create an entity class for the join table and mapping two separate one-to-many relationships. Like;
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; }
}
这篇关于身份和自定义表之间的多对多关系. EF7-代码优先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!