2012-07-07 56 views
0

我正在構建食譜/膳食計劃的申請,並且我遇到了一個問題,我似乎無法弄清楚。實體框架重複記錄第二次插入

我有措施,其中i保持使用的單位爲單位的表,我只想獨特的單位在這裏(用於購物清單計算等等)

但如果我使用單位從表在食譜上,第一次沒關係,沒有任何東西是以度量單位插入的,但是第二次我得到一個「重複」。

我懷疑它做的EntityKey,因爲主鍵是在SQL Server(2008 R2)

由於某種原因,它的工作原理來改變某些對象objectstate身份列(課程,見代碼),而不會產生重複的,但是這並不度量單位上工作

我的插入方法是這樣的:

public recipe Create(recipe recipe) 
    { 

     using (RecipeDataContext ctx = new RecipeDataContext()) 
     { 
      foreach (recipe_ingredient rec_ing in recipe.recipe_ingredient) 
      { 
       if (rec_ing.ingredient.ingredient_id == 0) 
       { 
        ingredient ing = (from _ing in ctx.ingredients 
             where _ing.name == rec_ing.ingredient.name 
             select _ing).FirstOrDefault(); 

        if (ing != null) 
        { 
         rec_ing.ingredient_id = ing.ingredient_id; 
         rec_ing.ingredient = null; 
        } 
       } 

       if (rec_ing.unit_of_measure.unit_of_measure_id == 0) 
       { 
        unit_of_measure _uom = (from dbUom in ctx.unit_of_measure 
              where dbUom.unit == rec_ing.unit_of_measure.unit 
              select dbUom).FirstOrDefault(); 
        if (_uom != null) 
        { 
         rec_ing.unit_of_measure_id = _uom.unit_of_measure_id; 
         rec_ing.unit_of_measure = null; 
        } 
       } 

       ctx.Recipes.AddObject(recipe); 
//for some reason it works to change object state of this, and not generate a duplicate 
       ctx.ObjectStateManager.ChangeObjectState(recipe.courses[0], EntityState.Unchanged); 
      } 



      ctx.SaveChanges(); 
     } 

     return recipe; 
    } 

我的數據模型是這樣的:

http://i.imgur.com/NMwZv.png

+0

你有沒有得到任何解決方案? – 2013-09-17 12:19:35

回答

0

我想這是在您嘗試保存配方時使用已分配的計量單位(FK!= 0)嗎?在這種情況下,您必須將其狀態更改爲Unchanged以避免重複。 AddObject將對象圖中的所有實體(不僅是Recipe)標記爲Added,因此如果圖中還包含現有實體,則必須將它們重新設置爲Unchanged以避免意外插入。

+0

我已經嘗試過這種方法,結果相同!它第一次工作,但第二次再次插入。 雖然我還沒有試圖標記現有的實體不變,只有新的 – Delysid 2012-07-12 18:00:15