11

In Linq To Sql, when updating one of my entities, Faculty, I am creating a new instance of the Faculty object, then initializing some of the properties with values supplied by the user.

If I attach this new object to the entity set, and submit changes, the properties that I didn't set take on the default value of whatever datatype they are.

How can I refresh the new object so that the properties that have been set keep their values and the properties that haven't been set get the values from the database?

Thanks

Ronnie Overby
  • 45,287
  • 73
  • 267
  • 346

2 Answers2

16

Did you try

context.Refresh(RefreshMode.OverwriteCurrentValues, faculty);

after submit changes where context is your linq2sql datacontext and faculty is the entity you want to refresh?

a_hardin
  • 4,991
  • 4
  • 32
  • 40
  • I've noticed it's also needed to do `yourBindingSource.ResetCurrentItem();` if you're refreshing the entity outside of the `CurrentChanged` event of the binding source. – Dor May 24 '11 at 19:06
1

What about retrieving the object from the database, then changing the appropriate values, then submitting the update?

CSharpAtl
  • 7,374
  • 8
  • 39
  • 53
  • I am maintaining some code that uses the attach method, and I am not quite sure why it wasn't written to do what you suggest to begin with. – Ronnie Overby May 22 '09 at 14:59
  • I think he is referring to creating a new entry in a table. – vidalsasoon May 22 '09 at 15:02
  • Oh! Now I remember. It's because there is a timestamp field called version. Doing what you suggested causes this error: Value of member 'Version' of an object of type 'Faculty' changed. A member that is computed or generated by the database cannot be changed. – Ronnie Overby May 22 '09 at 15:06
  • How is the date put in? Is it a default? I am confused why you would not be able to change a timestamp in the database. – CSharpAtl May 22 '09 at 15:12