第二次插入时的Entityframework重复记录

时间:2012-07-07 16:15:24

标签: entity-framework duplicates

我正在建立一个食谱/膳食计划申请,我遇到了一个我似乎无法弄清楚的问题。

我有一个测量单位的表格,其中我保留了使用过的单位,我只想要这里的唯一单位(用于购物清单计算等)

但是如果我在食谱中使用表中的单位,第一次没问题,没有以度量单位插入任何内容,但第二次我得到“重复”。

我怀疑它与entitykey有关,因为主键是sql server上的标识列(2008 r2)

由于某种原因,它可以更改某些对象(课程,请参阅代码)上的对象状态,并且不会生成重复,但这不适用于度量单位

我的插入方法如下所示:

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

1 个答案:

答案 0 :(得分:0)

我想当你试图用已经分配的UoM(FK!= 0)保存食谱时会发生这种情况?在这种情况下,您必须将其状态更改为Unchanged以避免重复。 AddObject将对象图中的所有实体(不仅Recipe)标记为Added,因此如果图表中还包含现有实体,则必须将它们设置回Unchanged以避免意外插入