0

内部に 3 つの異なる関連/ネストされたオブジェクトを持つオブジェクトがあります。フォームを介してそれらすべてを編集できます。私が今やろうとしているのは、オブジェクトの編集に戻ったときに、それらの子オブジェクトも編集できるようにしたいということです。これは非常にうまく機能します。ただし、保存しようとすると、子オブジェクトが複製されます。

たとえば、子オブジェクトの 1 つに対して次の EditorTemplate があります。

@model Vineyard.Core.Entities.UsedIngredient

<div class="usedIngredient form-inline">
@if (Model.UsedIngredientId != 0)
{
    @Html.HiddenFor(u => u.UsedIngredientId)
}
@if (Model.RecipeId != 0)
{
    @Html.HiddenFor(u => u.RecipeId)
}
@Html.LabelFor(r => r.Amount)
@Html.TextBoxFor(r => r.Amount)
@Html.LabelFor(r => r.IngredientName, "Name")
@Html.TextBoxFor(r => r.IngredientName)
@Html.HiddenFor(r => r.Delete, new {@class = "mark-for-delete"})
@Html.LinkToRemoveNestedForm("Remove", "div.usedIngredient", "input.mark-for-delete")
</div>

私はこのようなエンティティをDBに保存しています:

if (recipe.RecipeId == 0)
{
  context.Recipes.Add(recipe);
}
else
{
    Recipe dbObj = context.Recipes.Find(recipe.RecipeId);
    dbObj.Name = recipe.Name;
    dbObj.Subtitle = recipe.Subtitle;
    dbObj.Instructions = recipe.Instructions;
    dbObj.Serving = recipe.Serving;
    dbObj.PrepTime = recipe.PrepTime;
    dbObj.CookingTime = recipe.CookingTime;
    dbObj.RecipeImages = recipe.RecipeImages;
    dbObj.UsedIngredients = recipe.UsedIngredients;
    dbObj.Pairings = recipe.Pairings;
}
context.SaveChanges();

子オブジェクトの複製を防ぐにはどうすればよいですか?

4

1 に答える 1

0

子オブジェクトは の別のインスタンスによってフェッチされるDbContextため、Entity Framework はそれらを追跡できず、エンティティが既に存在することを知りません。

できることはRecipe、ナビゲーション プロパティの代わりに、オブジェクトに外部キーを入力することです。

dbObj.CookingTimeId = recipe.CookingTimeId
于 2013-07-22T21:31:46.963 に答える