title: Atomic Read and Write with Entity Framework
body: <p>I have two different processes (on different machines) that are reading and updating a database record. </p>
  
  <p>The rule I need to ensure is that the record must only be updated if the value of it, lets say is "Initial". Also, after the commit I would want to know if it actually got updated from the current process or not (in case if value was other than initial)</p>
  
  <p>Now, the below code performs something like:</p>
  
  <pre><code>var record = context.Records
               .Where(r =&gt; (r.id == id &amp;&amp; r.State == "Initial"))
               .FirstOrDefault();
  
  if(record != null) {
    record.State = "Second";
    context.SaveChanges();
  }
  </code></pre>
  
  <p>Now couple of questions</p>
  
  <p>1) From looking at the code it appears that after the record is fetched with state  "Initial", some other process could have updated it to state "Second" before this process performs SaveChanges. 
  In this case we are unnecessarily overwriting the state to the same value. Is this the case happening here ? </p>
  
  <p>2) If case 1 is not what happens then EntityFramework may be translating the above to something like </p>
  
  <pre><code>update Record set State = "Second" where Id = someid and State = "Initial"
  </code></pre>
  
  <p>and performing this as a transaction. This way only one process writes the value. Is this the case with EF default TransactionScope ?</p>
  
  <p>In both cases again how do I know for sure that the update was made from my process as opposed to some other process ?</p>
  
  <p>If this were in-memory objects then in code it would translate to something like assuming multiple threads accessing same data structure</p>
  
  <pre><code>Record rec = FindRecordById(id);
  lock (someobject)
  {
      if(rec.State == "Initial")
         {
            rec.State = "Second";
            //Now, that I know I updated it I can do some processing
         }
  }
  </code></pre>
  
  <p>Thanks</p>