2015-08-25 69 views
0

我在模型中映射了多對多關係。實體材料實體與許多實體相關,反之亦然。我爲此使用了中間表格(MaterialColor),其中只有兩個ID列引用每個表中的每個ID。實體框架和多對多映射:更新問題

這是它是如何在我的的DbContext實施方式配置:

 modelBuilder.Entity<Material>().HasMany<Color>(p => p.Colors).WithMany() 
      .Map(m => 
      { 
       m.ToTable("MaterialColor"); 
       m.MapLeftKey("MaterialId"); 
       m.MapRightKey("ColorId"); 
      }); 

到目前爲止,還沒有一個問題:除了現在我還有一個很多一對多的關係映射到材質與實體打印機:映射以相同的方式準確地進行配置:

 modelBuilder.Entity<Printer>().HasMany<Material>(p => p.Materials).WithMany() 
      .Map(m => 
      { 
       m.ToTable("PrinterMaterial"); 
       m.MapLeftKey("PrinterId"); 
       m.MapRightKey("MaterialId"); 
      }); 

,當我嘗試創建一個打印出現真正的問題呃實體及其與材料關係PrinterMaterial,但我不想插入新材料或新的顏色,當然,既不MaterialColor記錄

我已經一點一點地解決這個問題,並設法跳過它插入表中我不希望插入到你:

 _dbContext.Printers.Add(printer); 
     foreach (var material in printer.Materials) 
     { 
      foreach (var color in material.Colors) 
      { 
       _dbContext.Entry(color).State = EntityState.Unchanged; 
      } 
      _dbContext.Entry(material).State = EntityState.Unchanged; 
     } 
     _dbContext.SaveChanges(); 

的問題沒有完全解決,因爲它仍在努力插入MaterialColor。我不知道如何告訴EF跳過這種關係。

我嘗試這樣做:

 _dbContext.Entry(material).Property(m => m.Colors).IsModified = false; 

,但我得到這個錯誤:

Additional information: The property 'Colors' on type 'Material' is not a primitive or complex property. The Property method can only be used with primitive or complex properties. Use the Reference or Collection method.

這是有道理的,因爲 「顏色」 是一個集合。

如何讓EF忽略這種關係?

(PS:不帶顏色裝載材料是不是一種選擇)

編輯:添加打印機和printer.Materials初始化:

 var printer = new Printer(); 
     printer.Materials = new List<Material>(); 
     printer.Materials.Add(_materialService.GetMaterialById(materialId)); // this gives the material with many properties populated, like Colors. 
+0

您可以添加「打印機」和「打印機」。材料初始化,以及? –

+0

@TaherRahgooy補充。 – Silvestre

+0

當你保存這個,EF增加了新的顏色? –

回答

0

因爲我無法找到一個解決辦法這一點,我不得不刪除這個映射:

 modelBuilder.Entity<Material>().HasMany<Color>(p => p.Colors).WithMany() 
     .Map(m => 
     { 
      m.ToTable("MaterialColor"); 
      m.MapLeftKey("MaterialId"); 
      m.MapRightKey("ColorId"); 
     }); 

,並創建實體與兩個字段:

public class MaterialColor : ICacheableEntity 
{ 
    public virtual Material Material { get; set; } 
    public virtual Color Color { get; set; } 
    public int ColorId { get; set; } 
    public int MaterialId { get; set; } 
} 

這樣我可以設置物質實體的集合MaterialColor元素不變時,我想。