2013-07-22 69 views
0

我有一個對象,其中有3個不同的相關/嵌套對象。我可以通過表單編輯它們。 我現在想做的事情是,當我回到編輯對象時,我希望能夠編輯那些子對象 - 它工作得很好。除此之外,當我嘗試保存它時 - 子對象正在被複制。當父對象再次被保存時,.NET MVC-嵌套對象被複制

因此,對於一個例子,我對孩子的一隻以下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(); 

什麼會阻止我子對象被複制?

回答

0

您的子對象由另一個DbContext實例提取,所以實體框架無法跟蹤它們,也不知道實體已存在。

你可以做的是填寫的導航屬性代替了Recipe對象的外鍵:

dbObj.CookingTimeId = recipe.CookingTimeId