Partially updating object with EF Code First and ASP.NET MVC

微笑、不失礼 提交于 2019-12-03 04:53:18

Yes there is more elegant version:

public void Update(Person person, params Expression<Func<Person,object>>[] properties)
{
    context.People.Attach(person);

    DbEntityEntry<Person> entry = context.Entry(person);

    foreach (var property in properties)
    {
        entry.Property(property).IsModified = true;
    }

    person.ModifiedOn = DateTime.Now;
}

You will call the method this way:

[HttpPost]
public ActionResult Edit(Person person)
{
    if (ModelState.IsValid) 
    {

        personRepository.Update(person, p => p.FirstName, 
            p => p.LastName, p => p.Birthday);
        personRepository.Save();
        return RedirectToAction("Index");
    } 
    else 
    {
        return View(person);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!