views:

412

answers:

2

I am trying to update some object properties by calling UpdateModel(myObject, new[] { "stringprop1", "stringprop2", "intprop"}).

This is failing for an unknown reason. Several string properties are updating successfully. When I try to update an int property it fails. The new int value is being sent from an html select list on the view.

I can see the data from the view in my ValueProvider. The key matches the object's property name and the value is what I am expecting from the view (except that it's a string. I thought UpdateModel could handle simple type conversions.

When I call UpdateModel an InvalidOperationException is thrown, ONLY IF THE PROPERTY'S VALUE IS CHANGING.

Also, the object is a Linq To Sql generated object.

EDIT

Looking through Model State after calling TryUpdateModel, I see this exception on the property that I am having trouble with:

- Exception {"Operation is not valid due to the current state of the object."} System.Exception {System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException}

The value I am trying to update is a foreign key. Why can't I update this value? Thanks for any help?

EDIT 2

I found this: http://social.msdn.microsoft.com/Forums/en-US/linqtosql/thread/f9c4a01a-195a-4f2b-a1cb-e2fa06e28b25

I could have sworn that I have changed the key instead of the association property before, but whatever. What can be done in this MVC Model Binding situation?

+1  A: 

Screw it. I just did it the old fashioned way:

myObject.Skunk = db.Skunks.Single(s => s.ID == intprop);
Ronnie Overby
+1  A: 

I had this same problem and then realized it was the DataContext itself. I was saving this in session, rather than creating a new one with each request. Once I created the Context for each request, this error went away.

JasonW
I had the same issue as you describe and it was resolved by just instantiating a new DataContext -- I can't explain why though. Any ideas?
Andrew Flanagan