2016-11-24 96 views
1

我目前面臨的問題是,我有一個單一的實體(藝術家),它可以是一個「頭條新聞」或「支持行爲」多種關係。EF與同一實體的多對多關係

的這些表的的極端簡化版本:

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

正如我引入了兩個附加實體來滿足這些要求的中間溶液。

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

並介紹了下面的代碼在事件實體

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; } 
    } 

高於可行描述類似的東西,因爲它會給我的藝術家實體直接訪問?

+0

爲什麼你不能做到只用1結表吧:只需取下HeadlinerSupportAct實體,並使用以下? – Sampath

回答

1

如果我理解正確的話,你想切換到與隱結表many-to-many關聯。而且你需要兩個相同的實體之間的這種關聯。

好了,你可以在同一個實體之間配置兩個(或如你所願儘可能多的)協會以同樣的方式定義了一個協會 - 用流利的配置。

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"));