Entityframework duplicate record on second insert
Posted
by
Delysid
on Stack Overflow
See other posts from Stack Overflow
or by Delysid
Published on 2012-07-07T16:15:23Z
Indexed on
2012/07/09
9:15 UTC
Read the original article
Hit count: 151
entity-framework
|duplicates
I am building an application for recipe/meal planning, and i have come across a problem i cant seem to figure out.
i have a table for units of measure, where i keep the used units in, i only want unique units in here (for grocery list calculation and so forth)
but if i use a unit from the table on a recipe, the first time it is okay, nothing is inserted in units of measure, but the second time i get a "duplicate".
i suspect it has something to do with entitykey, because the primary key is identity column on the sql server (2008 r2)
for some reason it works to change the objectstate on some objects (courses, see code) and that does not generate a duplicate, but that does not work on the unit of measure
my insert methods looks like this :
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;
}
My datamodel looks like this :
© Stack Overflow or respective owner