This is a migrated thread and some comments may be shown as answers.

SaveChanges() will wipe out all the changes if there is a SQL Exception

3 Answers 91 Views
Development (API, general questions)
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Dilshod
Top achievements
Rank 1
Dilshod asked on 17 Aug 2016, 09:17 AM

Hi,

Is it possible to recover from a SQL error in SaveChanges() without losing data? Currently when I enter a duplicate value for a unique index, an exception is thrown and all changes in the context are rolled back. I don't want to lose changes in the context. I need the ability to correct the bad data and save again, without having to redo all the changes that were previously in the context.

Thanks,

Dilshod

3 Answers, 1 is accepted

Sort by
0
Ady
Telerik team
answered on 18 Aug 2016, 02:52 PM
Hi Dilshod,

 There is no easy way to achieve what you want.

You can call the OpenAccessContext.GetChanges() before calling 'SaveChanges' to return a 'ContextChanges' object which gives you all objects that are to be inserted,deleted or updated during the next call to SaveChanges.
If the call to SaveChanges fails you can use the ContextChanges object retrieved earlier to try and replay the changes.

Hope this helps.

Regards,
Ady
Telerik by Progress
 
Check out the latest announcement about Telerik Data Access vNext as a powerful framework able to solve core development problems.
0
Dilshod
Top achievements
Rank 1
answered on 19 Aug 2016, 10:34 AM

Hi Ady,

Thank you for responding.

Can you give me an example on how to do the replaying the changes to the context?

Thanks,

Dilshod

0
Ady
Telerik team
answered on 25 Aug 2016, 10:21 AM
Hello Dilshod,

 Sorry for the delayed response. 
 I did try to prepare an example with the 'GetChanges' API I mentioned in my previous post but I must admit that did not work. The values are rolled back to the original values when SaveChanges fails.

The only other way to maintain all values except the failing ones in the object is to maintain a copy of the values you are interested in and if SaveChanges fails you can replay the changes from this copy.

I have implemented a basic sample where I have implemented the Telerik.OpenAccess.IInstanceCallbacks.PreStore method to hook into the SaveChanges call. This method is called just before committing to the database. Here I make a copy of the fields which I need to replay.
If SaveChanges fails then I get the failed object and revert the changes.
Note that replaying changes can get complicated with collections and references.

Regards,
Ady
Telerik by Progress
 
Check out the latest announcement about Telerik Data Access vNext as a powerful framework able to solve core development problems.
Tags
Development (API, general questions)
Asked by
Dilshod
Top achievements
Rank 1
Answers by
Ady
Telerik team
Dilshod
Top achievements
Rank 1
Share this question
or