Lock a SQL server Table for a given time and check if it is locked

933 Views Asked by At

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.

1

There are 1 best solutions below

1
Sampath On BEST ANSWER

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