Thursday 25 June 2015

Entity framework multiple SaveChangesAsync await asynchronous operation Problem.

A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NotSupportedException: A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.

Source Error:


Line 569:                        ucontext.SaveChangesAsync();
Line 570:                        //remove previous entry from login attempt for both sucess and faliour login
Line 571:                        ucontext.loginattempt.RemoveRange(ucontext.loginattempt.Where(o => o.UserID == user.UserID && o.Success == 1).OrderByDescending(o => o.CreatedDate).Skip(5));
Line 572:                        ucontext.loginattempt.RemoveRange(ucontext.loginattempt.Where(o => o.UserID == user.UserID && o.Success == 0).OrderByDescending(o => o.CreatedDate).Skip(5));
Line 573:                        ucontext.SaveChangesAsync();


Solution
We can't use multiple asynchronous operation within function in which async and await is not defined. If we define method as async at the time of execution of async operation we could add await as prefix.


await ucontext.SaveChangesAsync();

or



Line 569:                        ucontext.SaveChanges();
Line 570:                        //remove previous entry from login attempt for both sucess and faliour login
Line 571:                        ucontext.loginattempt.RemoveRange(ucontext.loginattempt.Where(o => o.UserID == user.UserID && o.Success == 1).OrderByDescending(o => o.CreatedDate).Skip(5));
Line 572:                        ucontext.loginattempt.RemoveRange(ucontext.loginattempt.Where(o => o.UserID == user.UserID && o.Success == 0).OrderByDescending(o => o.CreatedDate).Skip(5));
Line 573:                        ucontext.SaveChangesAsync();