我正在構建食譜/膳食計劃的申請,並且我遇到了一個問題,我似乎無法弄清楚。實體框架重複記錄第二次插入
我有措施,其中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