views:

45

answers:

1

Hi I have a asp.net MVC Web Application. I have a database where i have made my model, i use Linq2SQL to build my Business Logic Layer. In my application i have a customer object, when i call my "editCystomer" page i pass in a Customer to populate the textBoxes:

[AcceptVerbs(HttpVerbs.Get)]
        [Authorize]
        public ViewResult EditCustomer(string id)
        {
            int customerId = Convert.ToInt32(id);
            CustomerRepository repository = new CustomerRepository();
            return View(repository.Load(customerId));
        }

When the user has changed in the textboxes i save my changed customer like this:

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();
            }
        }

Nothing fancy or unexpected so far, however in my save method:

public void Save(Customer customer)
        {
            if (customer.Id > 0)
                sdc.Refresh(System.Data.Linq.RefreshMode.KeepChanges, customer);
            else
                sdc.Customers.InsertOnSubmit(customer);

            sdc.SubmitChanges();
        }

...im getting an exception in my save (the update) that it cannot refresh the object (An object specified for refresh is not recognized. ). I have done this a million times before in other setups, how come its failing now? Any ideas?

A: 

The customer object you're sending to Save() is not part of the DataContext. You need to either get the object again, then call the Refresh().

Or you can do the following:

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();
}
Baddie