如何删除未附加的实体?

时间:2011-10-23 10:27:33

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

[AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Delete(int id)
        {
            CustomerDataContext cs = new CustomerDataContext();
            var query = cs.Customers.Where(m => m.CustId == id).Select(m => m);
            Customer cust = new Customer();
            foreach (var q in query)
            {

                cust.CustId = q.CustId;
                cust.Name = q.Name;
                cust.Salary = q.Salary;
                cust.JoiningDate = q.JoiningDate;
            }
            cs.Customers.DeleteOnSubmit(cust);
            cs.SubmitChanges();
            return View("Index");
        }

我收到以下错误:无法删除尚未附加的实体。

1 个答案:

答案 0 :(得分:1)

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Delete(int id)
{
    CustomerDataContext cs = new CustomerDataContext();
    var query = cs.Customers.Where(m => m.CustId == id).Select(m => m);
    foreach (var q in query)
    {
         cs.Customers.DeleteOnSubmit(q);
    }

    cs.SubmitChanges();
    return View("Index");
}