0

I want to lock a table for a given amount of time in SQL Server . I am using C# at code level. How can I achieve it, I also need to verify that the table is locked or not. I do not have much knowledge of locking tables in SQL Server. I want to achieve it using entity framework. Any help is much appreciated.

Madhur Maurya
  • 1,016
  • 4
  • 19
  • 42

1 Answers1

2

You can try as shown below.

using (var context = new YourContext())
    {
     using (var dbContextTransaction = context.Database.BeginTransaction())
     {
       //Lock the table during this transaction
       context.Database.ExecuteSqlCommand("SELECT 1 FROM YourTable WITH (TABLOCKX)
    WAITFOR DELAY '00:03:00'");

            //your work here

            dbContextTransaction.Commit();
      }
}

Note : The table lock will be released after it exits the BeginTransaction block

Sampath
  • 63,341
  • 64
  • 307
  • 441
  • 1
    a small edit. I should be `dbContextTransaction.Commit()` instead of `scope.Commit()` and Table in SQL command to be replaced by actual Table name – Madhur Maurya Oct 18 '16 at 07:03