title: How can I avoid duplicate rows from near-simultaneous SQL adds?
body: <p>My Razor 3 web app is creating multiple rows for the same foreign key Id, when multiple input comes in for the same Id, and I would like help on how to avoid this.</p>
  
  <p>The SQL Server table stores data about records in another table (it's ratings users have given about certain things, where there is also a table of users and a table of rate-able things, so the ratings table has a foreign key id for user, a foreign key id for the thing rated, and a value for the rating). When no rating has been given, there is no row for that user id &amp; thing id.</p>
  
  <p>When a user rates a thing, the code calls the server, which checks to see if that user has rated that thing before, and if so, it updates the row, but if not, it creates a new row:</p>
  
  <pre><code>// Get the member's rating for the thing, or create it.
  Member_Thing_Rating memPref = (from mip in _myEntities.Member_Thing_Rating
                                 where mip.thingID == thingId
                                 where mip.MemberID == memberId
                                 select mip).FirstOrDefault();
  if (memPref == null)
  {
     memPref = new Member_Thing_Rating();
     memPref.MemberID = memberId;
     memPref.thingID = thingId;
  
     _myEntities.Member_Thing_Rating.AddObject(memPref);
  }
  </code></pre>
  
  <p>Which works fine EXCEPT when the user sends two ratings for the same thing very quickly (which happens rather often), which results in the server creating two rows, because apparently it is multi-threaded and neither thread sees an existing row, so they both create a new one.</p>
  
  <p>So... how can I avoid this? </p>
  
  <ul>
  <li>I assume I can somehow (?) tell SQL Server to make a constraint that combos of <code>memberID</code> and <code>thingID</code> should be unique in this table, and then it would be SQL Server's job to auto-magically resolve the insertions and hopefully use the latest value.</li>
  </ul>
  
  <p>or</p>
  
  <ul>
  <li>I imagine I could somehow (?) tell this routine to lock the DB or become single-threaded so that one completes adding a row before the next call to the same routine is allowed to execute.</li>
  </ul>
  
  <p>I just don't know the syntax or UI/SQL steps to do either, despite a bit of looking. I think I prefer the thread lock solution, because I am more programmer than DB person, so I prefer my complexity in the code.</p>
  
  <p>Thanks for any help!</p>