是否可以使用相同的连接表创建2个M:M关系?
我遇到以下情况并收到例外情况:
Unhandled Exception: System.InvalidOperationException: Cannot create a relationship between 'ApplicationUser.ExpertTags' and 'UserTag.User', because there already is a relationship between 'ApplicationUser.StudyTags' and 'UserTag.User'. Navigation properties can only participate in a single relationship
在标签中:
public class Tag {
public Tag() {
Users = new List<UserTag>();
}
public int TagId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public ICollection<UserTag> Users { get; set; }
在ApplicationUser中:
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
StudyTags = new HashSet<UserTag>();
ExpertTags = new HashSet<UserTag>();
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string Location { get; set; }
public ICollection<UserTag> StudyTags { get; set; }
public ICollection<UserTag> ExpertTags { get; set; }
}
在UserTag(CLR加入)中:
public class UserTag
{
public string UserId { get; set; }
public ApplicationUser User { get; set; }
public int TagId { get; set; }
public Tag Tag { get; set; }
}
在ApplicationDbContext中:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<UserTag>()
.HasKey(x => new { x.UserId, x.TagId });
modelBuilder.Entity<UserTag>()
.HasOne(ut => ut.User)
.WithMany(u => u.StudyTags)
.HasForeignKey(ut => ut.UserId);
modelBuilder.Entity<UserTag>()
.HasOne(ut => ut.User)
.WithMany(u => u.ExpertTags)
.HasForeignKey(ut => ut.UserId);
modelBuilder.Entity<UserTag>()
.HasOne(ut => ut.Tag)
.WithMany(t => t.Users)
.HasForeignKey(ut => ut.TagId);
}
我是否需要创建单独的CLR类?类似于UserStudyTag
和UserExpertTag
?
谢谢!
答案 0 :(得分:1)
下一步到SQL DB。您希望表UserTag
包含一个UserId
字段。 EF应如何猜测,此表中的哪些记录与StudyTags
以及哪些ExpertTags
集合相关?
你应该复制一些东西。
将UserTag
拆分为两个表格(UserStudyTag
和UserExpertTag
),或在UserId
中创建两个UserTag
字段,例如ExpertUserId
, StudyUserId
。两者都可以为空,只有一个在每条记录中都有一些值。