title: How Can I Avoid Deadlocks With Slow Queries
body: <p>I have a WCF service that occasionally causes a database deadlock. My service allows you to submit applications to the council, also it allows you to load them again because the council can updated them. Each of the applications has a number of documents associated with it.</p>
  
  <p>So if a set of events like this occur on my service</p>
  
  <pre><code>1) Application #1 is submitted
  2) A document is uploaded for application #1
  3) Application #1 is loaded
  4) Part 2 above finishes
  </code></pre>
  
  <p>Deadlock at part 3. I believe the reason is that the document in part 2 takes a while to submit to the SQL server from the WCF service, and during this time it locks the table.</p>
  
  <p>So if we load from the database application #1, and the associated documents we get in trouble.</p>
  
  <p>I am using the entity framework. How can I solve this? All I really want to do is load the documents in this circumstance that are completely submitted and not run into the table being locked or anything.</p>
  
  <p>By the way this is the specific error I am getting,</p>
  
  <pre><code>Message: Transaction (Process ID 93) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
  </code></pre>
  
  <p><em>UPDATE:</em> I have had a couple of comments that I could change the order of operations. I cannot actually do that because part 2 and part 3 are from different calls to the WCF service. So it is up to the user of the service to order the operations. 'Ask them to change it' you say, but it is not that simple either. The order of the operations actually depends on the end user just happening to 'refresh' their browser at the right moment.</p>
  
  <p><em>Update #2:</em> I need some advice on how to replicate this issue. I have written a test application and part 2 above does block the operation in part 3, but the consequences for me is that operation 3 just blocks until operation 2 is finished, and then operation 3 finishes.</p>
  
  <p>So that means part 3 takes 1 minute 50 seconds instead of 3 which it normally would. Any ideas why it would be blocking for me, and not creating a deadlock? Could it relate to the amount of database traffic overall on that server seeing as I am using a test server, or could some database settings be affecting it?</p>