EF实体的部分更新

时间:2021-09-02 01:14:17

实现实体的部分更新
假设实体InfoHotel如下:

public class InfoHotel

{

  public int Id{get;set;}

  public string Name{get;set;}

  public string Address{get;set;

  public string Other1{get;set};

  public string Other1{get;set};

  public string Other2{get;set};

  public string Other3{get;set};

}

有个网页仅仅修改Name和Address,保存的Action如下

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,Address")] InfoHotel item)
{
  if (ModelState.IsValid)
  {
    var oldItem = db.InfoHotels.Find(this.KeyCorp);
    oldItem.Name = item.Name;
    oldItem.Address = item.KeyCardRW;
    oldItem.KeyPms = item.KeyPms;
    db.SaveChanges();
    return RedirectToAction("Index");
  }
  return View(item);
}

比较麻烦,可以改成

public ActionResult Edit([Bind(Include = "Id,Name,Address")] InfoHotel item)
{
  if (ModelState.IsValid)
  {
    var oldItem = db.InfoHotels.Find(this.KeyCorp)
db.Entry(oldItem).CurrentValues.SetValues(item);
    db.SaveChanges();
    return RedirectToAction("Index");
  }
  return View(item);
}