MVC更新Master-Child记录

时间:2015-01-21 19:29:17

标签: asp.net-mvc-4

我想在MVC中更新Master-Child记录集。

我的客户有一个ContactPerson,他有一个地址。 在我的EditView中,只有一些属性显示给用户进行编辑。 发布时,只有显示的数据放在我的对象中。所以我需要通过他们的ID获取数据库中的对象,然后映射编辑后的数据。

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Customer customer, ContactPerson contactPerson, Address address)
    {
        if (ModelState.IsValid)
        { 
            ContactPerson cp = db.ContactPersons.Where(c => c.Id == contactPerson.Id).Single();
            Address adr = db.Adresses.Where(a => a.id == address.id).Single();
            customer.ContactPerson = cp;
            cp.Addresses.Add(adr);
            db.Entry(customer).State = EntityState.Modified;

            cp.Surname = contactPerson.Surname;
            cp.LastName = contactPerson.LastName;
            cp.Email = contactPerson.Email;
            cp.Homepage = contactPerson.Homepage;
            ........
            db.Entry(cp).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(customer);
    }

这真的是这样做的方式,还是我错过了一些MVC框架的漂亮技巧;)

1 个答案:

答案 0 :(得分:0)

您可以使用AddOrUpdate

我不知道这是否属于"技巧",但你可以这样做(有些人可能认为这种方式不是最佳做法,但确实有效)。 请注意我用using语句允许您使用AddOrUpdate

using System.Data.Entity;
using System.Data.Entity.Migrations;

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Customer customer, ContactPerson contactPerson, Address address)
{
    if (ModelState.IsValid)
    { 
        ContactPerson cp = db.ContactPersons.Where(c => c.Id == contactPerson.Id).Single();
        Address adr = db.Adresses.Where(a => a.id == address.id).Single();
        customer.ContactPerson = cp; // There's a chance another db.SaveChanges() call should be made after this line.
        cp.Addresses.Add(adr);            
        db.AddOrUpdate(x => x.Id, cp); // The lambda expression is for the key                  
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(customer);
}

另一个注意事项:

如果您想要避免重新分配未显示的字段,我相信AddOrUpdate实际上只会更新您将值放入的字段。因此,将非显示为空并测试是否有效。