DataServiceContext , Detect if there are pending changes
Hi ,
I ran into this interesting scenario in the forums today .
How does one find out if there are any pending changes in the DataServiceContext that you have to submit to the store ?
This is quite simple actually .
The DataServiceContext has 2 collections called Entities and Links. These collections contain entities and links that are tracked by the context.
Given these collections , how does one know if any of them were changed on the client by the appropriate API ?
Lets look at the collections one by one ,
Entities
DataServiceContext.Entities gives you a List<EntityDescriptor> , each EntityDescriptor instance contains a State property.
If the State is anything other than Unchanged , then the changes made to the entity on the client side are not commited to the server.
This is because we change the states of the entities to Unchanged after you call SaveChanges on the context.
The basic state changes are :
UpdateObject –> Modified -> SaveChanges –> UnChanged
DeleteObject –> Deleted -> SaveChanges –> UnChanged
AddObject –> Added -> SaveChanges –> UnChanged
So , to find out if there are any entities in the DataServiceContext which have been changed and not saved,
you would write something like this :
bool pendingEntityChanges = dsContext.Entities.Any(ed => ed.State != EntityStates.Unchanged);
Links
DataServiceContext.Links gives you a List<LinkDescriptor> , each LinkDescriptor instance contains a State property ,
Links that point to collection properties
AddLink-> Added –> SaveChanges –> UnChanged
DeleteLink –> Deleted –> SaveChanges –> Detached
Links that point to reference properties
SetLink with Target not Null –> Modified –> SaveChanges –> UnChanged
SetLink with Target Null –> Modified –> SaveChanges –> Detached
To query for links which have not yet been saved , you would write :
bool pendingLinkChanges = dsContext.Links.Any(ld => ld.State != EntityStates.Unchanged);
and finally , the function to check if there are any unsaved changes ( Entities / Links ) in the context :
private bool HasUnsavedChanges(DataServiceContext dataContext){
//Check if any Entities are unsaved
return dataContext.Entities.Any(ed => ed.State != EntityStates.Unchanged)
//Check if any Links are unsaved
|| dataContext.Links.Any(ld => ld.State != EntityStates.Unchanged)
}