Preventing deadlock while logging via Entity Framework
tech: C#, Web App, Web API, Entity Framework, database We were getting database deadlock errors alot -- not all the time -- but alot. We tracked it down to logging each webapi call that occurs for a web app operation. One operation, like search, results in multiple webapi calls. The calls were being executed at the same time and therefore being logged at the same time. These simultaneous operations were contending with each other -- causing deadlock. The log code was innocent enough: Context.ActivityAudits.Add(model); Context.SaveChanges(); And the resulting SQL that Entity Framework generated and executed was not too surprising: exec sp_executesql N'INSERT [dbo].[ActivityAudit]([RequestId], [Method], [Path], [IpAddress], [Date], [StatusCode], [Error], [UserName]) VALUES (@0, @1, @2, @3, @4, @5, NULL, @6) SELECT [Id] FROM [dbo].[ActivityAudit] WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()' Well, the INSERT is totally expected. And, when you think about h...