net MVC Web 应用程序。我有一个数据库,我在其中制作了模型,我使用 Linq2SQL 来构建我的业务逻辑层。在我的应用程序中,我有一个客户对象,当我调用“editCystomer”页面时,我传入一个客户来填充文本框:
[AcceptVerbs(HttpVerbs.Get)]
[Authorize]
public ViewResult EditCustomer(string id)
{
int customerId = Convert.ToInt32(id);
CustomerRepository repository = new CustomerRepository();
return View(repository.Load(customerId));
}
当用户在文本框中发生更改时,我会像这样保存更改后的客户:
AcceptVerbs(HttpVerbs.Post)]
[Authorize]
public ActionResult EditCustomer(Customer customer)
{
ValidateCustomer(customer);
if (ModelState.IsValid)
{
CustomerRepository repository = new CustomerRepository();
repository.Save(customer);
return RedirectToAction("CreateCustomerDone");
}
else
{
return View();
}
}
到目前为止,没有什么花哨或意外的事情,但是在我的保存方法中:
public void Save(Customer customer)
{
if (customer.Id > 0)
sdc.Refresh(System.Data.Linq.RefreshMode.KeepChanges, customer);
else
sdc.Customers.InsertOnSubmit(customer);
sdc.SubmitChanges();
}
...我在保存(更新)中遇到异常,无法刷新对象(无法识别指定用于刷新的对象。)。我之前在其他设置中已经这样做了一百万次,为什么现在失败了?有什么想法吗?
最佳答案
您发送到 Save()
的客户对象不是 DataContext
的一部分。您需要再次获取该对象,然后调用 Refresh()
。
或者您可以执行以下操作:
public void Save(Customer customer)
{
if (customer.Id > 0)
{
Customer orig = sdc.Customers.GetOriginalEntityState(customer);
if(orig == null)
sdc.Attach(customer);
sdc.Refresh(System.Data.Linq.RefreshMode.KeepChanges, customer);
}
else
sdc.Customers.InsertOnSubmit(customer);
sdc.SubmitChanges();
}
关于asp.net-mvc - 更新 Linq2Sql 对象在 MVC 中出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3849627/