2016-11-29 61 views
0

是否可以使用相同的連接表創建2個M:M關係?如何使用相同的連接表創建多個多對多關係[EF7/Core]

我有以下的情況,我收到了異常:

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類?像UserStudyTagUserExpertTag

謝謝!

回答

1

退出SQL DB。你想要有UserTagUserId字段。 EF應如何猜測,本表中哪些記錄與StudyTags相關,哪些與ExpertTags集合有關?

你應該複製一些東西。

要麼分裂UserTag到兩個表(UserStudyTagUserExpertTag),或在UserTag提出兩個UserId領域,說ExpertUserIdStudyUserId。兩者都是可以空的,每個記錄中只有一個有一定的價值。

+0

謝謝。我結束了使用兩個單獨的表。 – Fedoranimus

相關問題