Data Conflict in LINQ

后端 未结 7 2065
不知归路
不知归路 2020-12-13 02:33

When making changes using SubmitChanges(), LINQ sometimes dies with a ChangeConflictException exception with the error message Row not found

7条回答
  •  一向
    一向 (楼主)
    2020-12-13 03:10

    row not found or changed is most of times a concurrency problem

    If a different user is changing the same record those errors popup because the record is already changed by that other user. So when you want to eliminate those errors you should handle concurrency in your application. If you handle concurrency well you won't get these errors anymore. The above code samples are a way to handle concurrency errors. Whats missing is that in case of a concurrency error you should put a refresh variable in those methods so when refresh is true the data needs to be refreshed on screen after the update so you will also see the update made by the other user.

        /// 
        ///     linq has optimistic concurrency, so objects can be changed by other users, while
        ///     submitted keep database changes but make sure users changes are also submitted
        ///     and refreshed with the changes already made by other users.
        /// 
        /// return if a refresh is needed.
        public bool SubmitKeepChanges()
        {
            // try to submit changes to the database.
            bool refresh = false;
            try
            {
                base.SubmitChanges(ConflictMode.ContinueOnConflict);
            }
    
            /* 
             * assume a "row not found or changed" exception, if thats the case:
             * - keep the database changes already made by other users and make sure
             * - this users changes are also written to the database
             */
            catch (ChangeConflictException)
            {
                // show where the conflicts are in debug mode
                ShowConflicts();
    
                // get database values and combine with user changes 
                base.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);
    
                // submit those combined changes again to the database.
                base.SubmitChanges();
    
                // a refresh is needed
                refresh = true;
            }
    
            // return if a refresh is needed.
            return refresh;
        }
    

提交回复
热议问题