实体框架更新实体?

时间:2012-08-14 22:36:58

标签: asp.net-mvc entity-framework

控制器

[HttpPost]
public ActionResult EditUserProfile(UserProfiles _postedUserProfile)
{
    UserProfiles orjinalUserProfile = entity.UserProfiles.Where(x => x.UserId == _postedUserProfile.UserId).Single();
    orjinalUserProfile.AboutMe = _postedUserProfile.AboutMe;
    orjinalUserProfile.Birthday = _postedUserProfile.Birthday;
    orjinalUserProfile.Comments = _postedUserProfile.Comments;
    ...... // there are lines more 
    entity.SaveChanges();
    return View();
}

我更新了上面的实体。但我认为这种方式并不好。是否有任何solutoin更新一行中的实体,例如插入操作,如entity.AddToUserProfiles

感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用ApplyCurrentValues方法。

以下是一个示例:ApplyCurrentValues in EF 4

基本上:

[HttpPost]
public ActionResult EditUserProfile(UserProfiles _postedUserProfile)
{
    UserProfiles orjinalUserProfile = entity.UserProfiles.Where(x => x.UserId == _postedUserProfile.UserId).Single();
    entity.UserProfiles.ApplyCurrentValues(_postedUserProfile);
    entity.SaveChanges();
    return View();
}
相关问题