开发者

Attached entity does not get update with new values when SaveChanges is called

Is there anything wrong with this code? My entity is not g开发者_运维技巧etting updated.

public ActionResult UpdateNota(string notas)
{
    if (Request.IsAjaxRequest())
    {
        RegistroEntities registroEntities = new RegistroEntities();
        Nota nota = JsonConvert.DeserializeObject<Nota>(notas);
        registroEntities.AttachTo("Notas",nota);
        registroEntities.ApplyCurrentValues("Notas", nota);
        registroEntities.SaveChanges(SaveOptions.DetectChangesBeforeSave);
        return Json(new {success=true});
    }
    return View();
}


Review the Entity Framework documentation entitled Working with Objects, in particular the section on Attaching and Detaching Objects.

In this case, you're calling AttachTo, which places the entity in the Unchanged state.

Then you call ApplyCurrentValues, which copies all the values in the entity over its own values; any values that have a different value are marked as modified. (Note that since each value is just copied over itself, none of them have a different value, so the entity remains in the Unchanged state).

Finally, you call SaveChanges. Since the entity is in an Unchanged state, there is nothing to do.

The MSDN documentation links at the beginning of this answer contain information about the correct way to do this (note that adding the entity uses a different solution than updating the entity).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜