Usually in a SOA model, you will have a service operation that retrieves the data to send it back to the client and then destroys the datacontext and forgets about the client all together.
Without the original datacontext or the original data you can not really track changes. That’s to say you can not move this data across tiers or layers and expect to track changes unless you pass the data context as well, the client should maintain the reference to the data context and send it back with the request for update. In other words, Your data context with ObjectTrackingEnabled = True must be kept alive until the data comes back modified in order for object tracking to work.
Since, The DataContext class is not designed to survive across layers and tiers. You should think of it as a sort of database connection object—to grab as late as possible and release as soon as possible. Entities queried through a given context remain bound to that context for eternity—when object tracking is enabled. You can’t attach an external entity object to a data context different from the one which created the entity.
Cached data remains available even after the data context has been disposed of. What if you modify this data in memory and then want to save changes back to the database? To submit changes to the SQL Server table, you still need a data context object. You have a few options:
1- Caching the original data context,
2- Implementing the data context as a singleton
3- Use a fresh instance of the data context class.
The DataContext class is not designed for being thread safe. So any use of it that configures usage from within different threads is not recommended.
The DataContext class is designed to be a short-lived, lightweight object that you use and dispose of as soon as possible. Yes, it is much like an ADO.NET database connection object.
Using a fresh instance is definitely the way to go. to use a fresh instance the client should send the original data as well as the modified data to the service. When the service receives both original data and modified data, the original data need to be attached to a fresh context and then the modified data updated into the context.
if your original data is in a List called OriginalData
and your modified data is in a list called ModifiedData
and your table is called MyTable
and your primay key is called Primary key
if the data context is declared as dc
then you can use a line like this to implement the attach and update of the modified data
OriginalData.ForEach(p=> dc.MyTable.Attach(ModifiedData.Where(x=> x.PrimaryKey == p. PrimaryKey).First(), p ));
You can get the modified object by simply calling
dc.MyTable.Context.GetChangeSet().Updates
To get the deleted objects
dc.MyTable.Context.GetChangeSet().Deletes
Inserted objects
dc.MyTable.Context.GetChangeSet().Inserts