如何使用相同的连接表创建多个多对多关系[EF7 / Core]

时间:2016-11-29 22:23:02

标签: entity-framework entity-framework-core .net-core

是否可以使用相同的连接表创建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类?类似于UserStudyTagUserExpertTag

谢谢!

1 个答案:

答案 0 :(得分:1)

下一步到SQL DB。您希望表UserTag包含一个UserId字段。 EF应如何猜测,此表中的哪些记录与StudyTags以及哪些ExpertTags集合相关?

你应该复制一些东西。

UserTag拆分为两个表格(UserStudyTagUserExpertTag),或在UserId中创建两个UserTag字段,例如ExpertUserIdStudyUserId。两者都可以为空,只有一个在每条记录中都有一些值。