I was stunned that Microsoft has made disconnected updates with Linq so difficult. Didn’t they realize that a large chunk of their developers would be using ASP.NET or WCF?
Some of the more cryptic errors are:
“An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.”
“An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.”
Changing update policies didn’t work. Adding timestamp columns didn’t work. Crying, while it felt good, didn’t work. What worked? A couple hours of forum crawling just to find one good post, here. Sidar Ok, you are my hero of the day. If I was the ruler of a small country, August 18th would be Sidar Ok Day.
Happiness Returns
This gist of it is to turn off object tracking for the retrieval data context. You would think that there would be no tracking involved after that data context is disposed of, but c’est la vie. Could be that some garbage disposal needed to happen or Linq’s Table attribute is adding some wierd exentsibility. I dunno.
In this sample, I’m using a simple AccountType table. I am retrieving, disconnecting, modifing, and saving.
Sample Code
Sub DisconnectedAccountTypeUpdate()
Dim acctType As Linq2SqlTestApp.DAL.AccountType
Dim originalAcctType As Linq2SqlTestApp.DAL.AccountType‘Retrieve and Disconnect
Using dc As New Linq2SqlTestApp.DAL.MyDatabase(My.Settings.MyDatabaseConnectionString)
dc.Log = Console.Out
dc.ObjectTrackingEnabled = False
acctType = dc.GetTable(Of AccountType).Single(Function(g) g.AccountType1 = “RESOLD”)
originalAcctType = dc.GetTable(Of AccountType).Single(Function(g) g.AccountType1 = “RESOLD”)
End Using‘Modify disconnected object.
acctType.OrderBy += 1‘Update
Using dc As New Linq2SqlTestApp.DAL.MyDatabase(My.Settings.MyDatabaseConnectionString)
dc.Log = Console.Out
dc.AccountType.Attach(acctType, originalAcctType)
dc.SubmitChanges()
End UsingEnd Sub