I have a database table and a corresponding entity class (POCO with change tracking Proxy) with a member which acts as a counter:
class MyEntity
{
public virtual int ID { get; set; }
public virtual int Counter { get; set; }
}
There is a function in my web application which must fetch this entity by ID, read the Counter
(which is then used to be assigned to other objects), increment it and write the entity back to the database, like so:
public int GetNewCounter(int ID)
{
int newCounter = 0;
using (MyObjectContext ctx = new MyObjectContext())
{
MyEntity ent = ctx.MyEntities.Where(e => e.ID == ID).Single();
++ent.Counter;
newCounter = ent.Counter;
ctx.SaveChanges();
}
return newCounter;
}
// newCounter is now used for other stuff
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).
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?
What options do I have to implement this requirement with Entity Framework (EF 4)?
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.
Thank you in advance!