title: How to ensure that the WCF service will not communicate to the database in parallel
body: <p>I have a <code>WCF</code> service, which should return objects from database, but each entity should be returned only once. I would like to avoid scenario, where many clients are using service, and they can get same <code>Request</code> entity.</p>
  
  <pre><code>public Request GetChangeRequest()
  {
      using (var context = new Data.Core.Context())
      {
          var request = context.Requests
              .Where(r =&gt; r.IsAvaible)
              .FirstOrDefault();
  
          if (request != null)
          {
              request.IsAvaible = false;
              context.SaveChanges();
          }       
          return request;
      }
  }
  </code></pre>
  
  <p>I am really wondering if there is a reason to give additional security like locking database. To do this I have managed something like this:</p>
  
  <pre><code>public Request GetChangeRequest()
  {
      using (var context = new Data.Core.Context())
      {
          context.OnLock&lt;Request&gt;(context.GetTableName&lt;Request&gt;(), () =&gt;
          {
              var request = context.Requests
                  .Where(r =&gt; r.IsAvaible)
                  .FirstOrDefault();
  
              if (request != null)
              {
                  request.IsAvaible = false;
                  context.SaveChanges();
              }       
              return request; 
          });
      }
  }
  
  public static class DBContextExtensions
  {
      public static string GetTableName&lt;T&gt;(this DbContext context) where T : class
      {
          var type = typeof(T);
          var entityName = (context as System.Data.Entity.Infrastructure.IObjectContextAdapter).ObjectContext.CreateObjectSet&lt;T&gt;().EntitySet.Name;
          var tableAttribute = type.GetCustomAttributes(false).OfType&lt;System.ComponentModel.DataAnnotations.Schema.TableAttribute&gt;().FirstOrDefault();
  
          return tableAttribute == null ? entityName : tableAttribute.Name;
      }
  
      public static T OnLock&lt;T&gt;(this DbContext context, string tableName, Func&lt;T&gt; action)
      {
          T res;
          using (DbContextTransaction scope = context.Database.BeginTransaction())
          {
              context.Database.ExecuteSqlCommand($"SELECT TOP 1 Id FROM {tableName} WITH (TABLOCKX, HOLDLOCK)");
              res = action.Invoke();
              scope.Commit();
          }
          return res;
      }
  }
  </code></pre>
  
  <p>I couldn't reproduce scenerio, when two request entity are returned to two different clients. Does that mean, that <code>WCF</code> service performs requests sequentially? </p>