2017-02-05 63 views
0

問題映射EF多,我有兩個POCO實體類的同一關係類型

public class Model 
{ 
    public long Id { get; set; } 

    public string Name { get; set; } 
    public string Description { get; set; } 


    // Relationships  
    public virtual ICollection<Shoot> PhotoSets { get; set; } 
    public virtual ICollection<Shoot> FilmSets { get; set; } 

} 

public class Shoot 
{ 
    public long Id { get; set; } 

    public string Name { get; set; } 
    public string Description { get; set; } 
    public string ShootType { get; set; } 

    // Relationships 
    public long ModelId { get; set; } 
    public virtual Model Model { get; set; } 

} 

所以我只想用多種類型,型號採用ICollection的導航屬性dfined一個表。如果我按照慣例讓EF生成,它將創建Model_dId作爲我想避免的額外屬性。在我流利的映射ModelConfiguration類我嘗試這樣做:

this.HasMany(m => m.FilmSets) 
    .WithRequired(sh => sh.Model) 
    .HasForeignKey(sh => sh.ModelId); 

this.HasMany(m => m.PhotoSets) 
    .WithRequired(sh => sh.Model) 
    .HasForeignKey(sh => sh.ModelId); 

,並得到Additional information: Schema specified is not valid. Errors: The relationship 'PronHunter.Database.Model_FilmSets' was not loaded because the type 'PronHunter.Database.Shoot' is not available.

我從ShootConfiguration試圖與界定這兩個路徑:

this.HasRequired(sh => sh.Model) 
    .WithMany(m => m.PhotoSets) 
    .HasForeignKey(sh => sh.ModelId); 

this.HasRequired(sh => sh.Model) 
    .WithMany(m => m.FilmSets) 
    .HasForeignKey(sh => sh.ModelId); 

查詢第一次,當它建立一個數據庫,但它仍然會生成額外的Model_Id列。實際上,我也嘗試將ModelId重命名爲ModelaaaId,但隨後我得到了三列ModelaaaId,ModelId和Model_id,因此EF無視我的顯式命名。

所以我的感覺是這是一個多對多的場景,但我嘗試了一些例子,但是我沒有看到任何intellisense上的MapLeftColumn,並且它對許多場景來說都不是直的。對於我想定義的manies來說,就像我在T-SQL中定義兩個內部連接一樣。

任何人都知道我應該怎麼做呢?

+0

嗯,也許我需要按照每個層次結構。雖然我沒有特定的字段。他們都是相同的形狀,所以從一些基本類型繼承似乎矯枉過正,但沒有額外的屬性 –

回答

0

看起來好像你都設置爲使用TPH與ShootType爲你的鑑別 - 派生從Shoot兩種新類型(例如FilmSetPhotoSet)然後配置爲this MSDN article描述的鑑別ShootType。然後,您可以使用這些類型的兩個不同的集合:

public class FilmSet : Shoot {} 
public class PhotoSet : Shoot {} 

// DbContext model configuraiton 
modelBuilder.Entity<Shoot>() 
    .Map<FilmSet>(m => m.Requires("ShootType").HasValue("Film Set")) 
    .Map<PhotoSet>(m => m.Requires("ShootType").HasValue("Photo Set")); 

public class Model 
{ 
    public virtual ICollection<FilmSet> FilmSets { get; set; } 
    public virtual IColelction<PhotoSet> PhotoSets { get; set; } 
} 

或者,您也可以創建兩個映射的特性來過濾單一映射的集合。您將需要使用單個映射集合進行添加/刪除操作,但是:

public virtual ICollection<Shoot> Shoots { get; set; } 
[NotMapped] 
public IEnumerable<Shoot> PhotoSets { 
    get { return Shoots?.Where(s => s.ShootType == "Photo Set"); } 
} 
public IEnumerable<Shoot> FilmSets { 
    get { return Shoots?.Where(s => s.ShootType == "Film Set"); } 
} 
+0

感謝您的答覆。我的兩個亞型實際上完全相同,是TPH唯一的出路嗎? –

+0

這是唯一一個可以在不違反3NF的情況下使用TPH的時間!您可以創建兩個未映射的屬性來過濾單個映射的集合,但您必須使用該單個集合進行添加/刪除操作。 – Moho

相關問題