title: Concurrent access of records in Entity Framework
body: <p>I am working on finding an elegant solution to handle concurrency conflict in Entity Framework. </p>
  
  <p>My table for administered drugs has a few columns like drug name, dose, frequency, administer method, notes and few more. An operator can modify fields like dose, frequency, administer method etc after reviewing records OR they can just add notes. </p>
  
  <p>SQL Server database is being used by us. </p>
  
  <p>I have added a column <code>LastUpdated</code> of type <code>timestamp</code>. I'm using this column to raise <code>DbUpdateConcurrencyException</code>. The <code>ConcurrencyMode</code> for the <code>LastUpdated</code> column has been set to <code>Fixed</code> in the entity designer.</p>
  
  <p>The code snippet from my controller class :</p>
  
  <pre><code>// drugId and strNotes are passed from edit screen
  DataAccessLayer.Dal dal= new DataAccessLayer.Dal();
  
  // Select record
  DrugDetail drugDetail = (from drugRow in dal.DrugDetails
                           where drugRow.id == drugId
                           select drugRow).ToList&lt;DrugDetail&gt;()[0];
  
  // Assign notes 
  drugDetail.Notes = strNotes;
  
  try
  {
      dal.SaveChanges();
  }
  catch(DbUpdateConcurrencyException ex)
  {
      ((IObjectContextAdapter)dal).ObjectContext.
               Refresh(System.Data.Objects.RefreshMode.StoreWins, drugDetail);
  
      // Set the notes data again
      drugDetail.Notes = strNotes;
  
      // Is it possible that DbUpdateConcurrencyException occur again here
      dal.SaveChanges();
  }
  </code></pre>
  
  <p>I'm worried that concurrency conflict can again occur when <code>SaveChanges()</code> is called from catch block. I think it is possible that another user can  modify and save the same record between refresh and save in catch block. </p>
  
  <p>Is my worried valid? I could not find any concrete answer by searching on net. </p>
  
  <p>I was thinking to create this scenario in my test environment and verify behavior but then thought to check in forum here first. </p>
  
  <p>Thanks for help.  </p>
  
  <p>As requested DrugDetail class is added here:</p>
  
  <pre><code>public partial class DrugDetail
  {
      public long id { get; set; }
      public string DrugName { get; set; }
      public Nullable&lt;decimal&gt; Dose { get; set; }
      public Nullable&lt;byte&gt; Frequency { get; set; }
      public string Method { get; set; }
      public string Notes { get; set; }
      public byte[] LastUpdated { get; set; }
  }
  </code></pre>