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

4 posts, 0 answers
  1. Dilshod
    Dilshod avatar
    23 posts
    Member since:
    Feb 2012

    Posted 17 Aug Link to this post

    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

  2. Ady
    Admin
    Ady avatar
    588 posts

    Posted 18 Aug Link to this post

    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.
  3. DevCraft banner
  4. Dilshod
    Dilshod avatar
    23 posts
    Member since:
    Feb 2012

    Posted 19 Aug in reply to Ady Link to this post

    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

  5. Ady
    Admin
    Ady avatar
    588 posts

    Posted 25 Aug Link to this post

    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.
Back to Top