2012-07-07 2 views
0

나는 요리법/식사 계획을위한 응용 프로그램을 작성하고 있습니다. 알아낼 수없는 문제가 발생했습니다.Entityframework 두 번째 삽입물에 중복 기록

내가에서 사용 된 단위를 계속 측정의 단위 테이블이, 난 단지 여기에 고유 한 단위를 원하는

(등 식료품 목록 계산 및 대한)하지만 난 테이블에서 단위를 사용하는 경우 조리법에, 처음에는 괜찮아요, 아무 것도 측정 단위에 삽입되지 않지만 두 번째로 "중복"을 얻습니다.

내가 기본 키가 어떤 개체에 대한 objectstate을 변경하기 위해 노력하고 어떤 이유로 SQL 서버 (2008 R2)

에 ID 열이 있기 때문에, entitykey 함께 할 수있는 뭔가가 의심 (과정, 코드를 볼 수) 그 중복을 생성하지 않습니다, 그러나 그것은 측정 단위에서 작동하지 않습니다

내 삽입 방법 은 다음과 같습니다

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

해결책을 얻었습니까? –

답변

0

UoM이 이미 할당 된 (FK! = 0) 레시피를 저장하려고 할 때 발생하는 것 같습니까? 이 경우 중복을 피하려면 상태를 Unchanged으로 변경해야합니다. AddObject은 오브젝트 그래프의 모든 엔티티를 Added으로 표시합니다 (예 : Recipe 만 해당). 그래도 그래프에 기존 엔티티가 포함되어 있으면 예기치 않은 삽입을 피하기 위해 다시 Unchanged으로 설정해야합니다.

+0

나는 그 결과를 가지고 그러한 접근법을 시도했다! 처음 작동하지만 두 번째로 다시 삽입됩니다. 기존 엔티티를 변경하지 않고 표시하려고 시도하지는 않았지만 새로운 엔티티 만 변경하려고했습니다. – Delysid

관련 문제