0

I have multiple services using same table and i want to lock table using EF,if some service is already using it.

I try to do this with the help of below solution but it doesn't work

How can I lock a table on read, using Entity Framework?

For more Information

I try to use this code from "Service 1" at the same time I have use "Service 2" call same function but it still retrieve data from table.

** I want "Service 1" call function then table have be lock and "Service 2" can't retrieve data or do anything is it possible to this?

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.RepeatableRead }))
{
       var newUrl = dbEntity.URLs.FirstOrDefault(url => url.StatusID == (int) URLStatus.New);
       if(newUrl != null)
       {
            newUrl.StatusID = (int) URLStatus.InProcess;
            dbEntity.SaveChanges();
       }

       scope.Complete();
}
Witchayanin
  • 57
  • 2
  • 8
  • 1
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. – TheGameiswar Aug 28 '17 at 11:37
  • thank you. I will add more information. – Witchayanin Aug 28 '17 at 13:49
  • Duplicate question. See https://stackoverflow.com/questions/13404061/how-can-i-lock-a-table-on-read-using-entity-framework – Henrik Høyer Feb 04 '20 at 22:21
  • Does this answer your question? [How can I lock a table on read, using Entity Framework?](https://stackoverflow.com/questions/13404061/how-can-i-lock-a-table-on-read-using-entity-framework) – Henrik Høyer Feb 04 '20 at 22:22

1 Answers1

0

No Transaction Isolation Level does that. The easiest way to do that is with an Application Lock. An Application Lock is like a global Mutex that can allow only a single client computer to run a piece of code. Note that this code doesn't have to be database code. You could use an Application Lock to give a client exclusive access to a file, or other resource.

Like this:

eg

using (var tran = db.Database.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
{
    var lockName = "MyLock";
    db.Database.ExecuteSqlCommand($"exec sp_getapplock '{lockName}', 'exclusive'");

    // do stuff

    tran.Commit();
}
adiga
  • 34,372
  • 9
  • 61
  • 83
David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67