asp.net-mvc - 更新 Linq2Sql 对象在 MVC 中出现异常

标签 asp.net-mvc linq-to-sql

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/

相关文章:

c# - 避免解析数据库中的 xml 字段

c# - MVC Entity Framework DropDownListFor<>

c# - 如何使用 ASP.NET MVC 进行 HTTP 调用?

c# - 从 Linq 到 Sql 的随机行

asp.net-mvc - 使用 Linq to Sql 选择多个表

c# - Linq to SQL 为两个不同的表两次连接到同一个表

c# - 语法错误,Razor 中预期为 '>'

c# - LINQ - 当值为 NULL 时排除过滤器

.net - 使用 PostgreSQL 的 Linq To Sql

javascript - 如何从 mvc View 调用 javascript 函数