title: Reading, incrementing and writing back a counter which is unique across multiple users (in EF 4)
body: <p>I have a database table and a corresponding entity class (POCO with change tracking Proxy) with a member which acts as a counter:</p>
  
  <pre><code>class MyEntity
  {
      public virtual int ID { get; set; }
      public virtual int Counter { get; set; }
  }
  </code></pre>
  
  <p>There is a function in my web application which must fetch this entity by ID, read the <code>Counter</code> (which is then used to be assigned to other objects), increment it and write the entity back to the database, like so:</p>
  
  <pre><code>public int GetNewCounter(int ID)
  {
      int newCounter = 0;
      using (MyObjectContext ctx = new MyObjectContext())
      {
          MyEntity ent = ctx.MyEntities.Where(e =&gt; e.ID == ID).Single();
          ++ent.Counter;
          newCounter = ent.Counter;
          ctx.SaveChanges();
      }
      return newCounter;
  }
  // newCounter is now used for other stuff
  </code></pre>
  
  <p>Two users or more could do this at the same time (with the entity of the same ID) and I have to make sure that they don't read and use the same Counter (so the second user should not be able to acquire a counter before the first user has stored the incremented counter back to the database).</p>
  
  <p>Is it possible to "lock" an Entity before it is read and release the lock after writing back the change of the counter and then check for a lock when another user tries to read the same Entity? Is that a reasonable pattern at all?</p>
  
  <p>What options do I have to implement this requirement with Entity Framework (EF 4)?</p>
  
  <p>I am very unfamiliar with the concurrency features and ideas in SQL Server and Entity Framework and would appreciate to get help into the right direction with this specific problem.</p>
  
  <p>Thank you in advance!</p>