views:

883

answers:

2

This has to be a frequent question, but not on SO yet, so it seems. I am using Linq to SQL for an application that allows a variety of data changes to my in-memory model, and the changes will then get placed into a queue for asynchonous processing. So, I am not worried about updates (yet). Changes to various parts of the data can be made through modal popups on the web page. Some are grid-based, others are just attributes. I am running into a problem with changes not surviving postback cycles. Obviously, I don't want to persist anything to the database until all changes are made and the user submits the page.

The route that I have chosen so far is:

  • I disabled deferred loading
  • I create a [serializable] partial class for my root object
  • I put the thing into the session and retrieve it in the onload event

This seems to work in principle. However, when I try to update some of the children's properties after retrieving the object from the session

p.PhysicianSpecialties[0].physician_specialty_code = 
    ddlSpecialty.SelectedItem.Value;

I get this error:

Operation is not valid due to the current state of the object.

The error is caused by this method call in the generated Linq setter method:

this.SendPropertyChanging();

Other properties get updated just fine:

p.PhysicianNames[0].first_name = txtFirstName.Text.ToUpper();

This does not cause an error.

My questions: Am I fundamentally on the wrong track? Is there a better way of doing this? What causes the error?

Update: The exception is 'System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException'. I think I am on to something, but I don't know the solution yet.

+1  A: 

I got the solution from MSDN. The issue is, and it is explained better in this thread than I can do it, that one cannot change an association unilaterally, but has to do it on both ends, by assigning a new child object, not just by a changing the id:

p.PhysicianSpecialties[0].PhysicianSpecialtyLookup = db.PhysicianSpecialtyLookups.Single(c => (c.physician_specialty_code == ddlSpecialty.SelectedItem.Value));

cdonner
A: 

And how does one go about doing that if using data binding? I have a drop down list in a data grid view that started throwing this error when I change the drop down value. This makes me think I have to either delete the association or not use data binding.

What are you binding to the drop-down?
cdonner