我正在构建食谱/膳食计划的申请,并且我遇到了一个问题,我似乎无法弄清楚。实体框架重复记录第二次插入
我有措施,其中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;
}
我的数据模型是这样的:
你有没有得到任何解决方案? – 2013-09-17 12:19:35