How can I reject all changes in a Linq to SQL's DataContext?

后端 未结 10 1054
礼貌的吻别
礼貌的吻别 2020-11-27 18:57

On Linq to SQL\'s DataContext I am able to call SubmitChanges() to submit all changes.

What I want is to somehow reject all changes in the datacontext and rollback a

10条回答
  •  一个人的身影
    2020-11-27 19:16

    public static class DataContextExtensions
    {
        /// 
        ///     Discard all pending changes of current DataContext.
        ///     All un-submitted changes, including insert/delete/modify will lost.
        /// 
        /// 
        public static void DiscardPendingChanges(this DataContext context)
        {
            context.RefreshPendingChanges(RefreshMode.OverwriteCurrentValues);
            ChangeSet changeSet = context.GetChangeSet();
            if (changeSet != null)
            {
                //Undo inserts
                foreach (object objToInsert in changeSet.Inserts)
                {
                    context.GetTable(objToInsert.GetType()).DeleteOnSubmit(objToInsert);
                }
                //Undo deletes
                foreach (object objToDelete in changeSet.Deletes)
                {
                    context.GetTable(objToDelete.GetType()).InsertOnSubmit(objToDelete);
                }
            }
        }
    
        /// 
        ///     Refreshes all pending Delete/Update entity objects of current DataContext according to the specified mode.
        ///     Nothing will do on Pending Insert entity objects.
        /// 
        /// 
        /// A value that specifies how optimistic concurrency conflicts are handled.
        public static void RefreshPendingChanges(this DataContext context, RefreshMode refreshMode)
        {
            ChangeSet changeSet = context.GetChangeSet();
            if (changeSet != null)
            {
                context.Refresh(refreshMode, changeSet.Deletes);
                context.Refresh(refreshMode, changeSet.Updates);
            }
        }
    }
    

    Refer to Linq to SQL - Discard Pending Changes

提交回复
热议问题