EF与同一实体的多对多关系

时间:2016-11-24 08:32:58

标签: c# entity-framework entity-framework-6 many-to-many

我目前面临的问题是,我有单一实体(艺术家),可以是多人关系中给定事件的“头条新闻”或“支持行为”。

这些表的极简化版本:

 +----------------+     +----------------+
 | Artist         |     | Event          |
 +----------------+     +----------------+
 | ArtistId       |     | EventId        |
 | ExternalId     |     | Name           |
 | Name           |     |                |
 +----------------+     +----------------+

作为一种中间解决方案,我引入了两个额外的实体来满足这些要求。

 +----------------+     +----------------+
 | Headliner      |     | SupportAct     |
 +----------------+     +----------------+
 | ArtistId       |     | ArtistId       |
 | EventId        |     | EventId        |
 +----------------+     +----------------+

并在Event实体中引入了以下代码

    private ICollection<Headliner> _headliners;

    public virtual ICollection<Headliner> Headliners
    {
        get { return _headliners ?? (_headliners = new Collection<Headliner>()); }
        protected set { _headliners = value; }
    }

    private ICollection<SupportAct> _supportActs;

    public virtual ICollection<SupportAct> SupportActs
    {
        get { return _supportActs ?? (_supportActs = new Collection<SupportAct>()); }
        protected set { _supportActs = value; }
    }

我想要完成的是一个更简化的解决方案,看起来就像你在下面找到的那样。

代码将减少到下面你会发现的东西。但这是不允许的......

    private ICollection<Artist> _headliners;

    public virtual ICollection<Artist> Headliners
    {
        get { return _headliners ?? (_headliners = new Collection<Artist>()); }
        protected set { _headliners = value; }
    }

    private ICollection<Artist> _supportActs;

    public virtual ICollection<Artist> SupportActs
    {
        get { return _supportActs ?? (_supportActs = new Collection<Artist>()); }
        protected set { _supportActs = value; }
    }

上面描述的内容是否可行,因为它可以让我直接访问Artist实体?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望切换到隐式联结表的many-to-many关联。而且你需要在同一个实体之间进行两次这样的关联。

那么,您可以使用与流畅配置相同的方式配置相同实体之间的两个(或任意多个)关联。只需删除HeadlinerSupportAct实体,然后使用以下内容:

modelBuilder.Entity<Event>()
    .HasMany(e => e.Headliners)
    .WithMany()
    .Map(a => a.ToTable("Headliner")
        .MapLeftKey("EventId")
        .MapRightKey("ArtistId"));

modelBuilder.Entity<Event>()
    .HasMany(e => e.SupportActs)
    .WithMany()
    .Map(a => a.ToTable("SupportAct")
        .MapLeftKey("EventId")
        .MapRightKey("ArtistId"));