Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking tables in Entity Framework

I have an SQL Database with a table that I would like to lock. I'm using Entity Framework. Basically, there are a number of processes that each want to write to the database concurrently. Each of them wants to update a row in some table. However, I want only one of them to be able to do this at the same time.

Is there a way of locking an entire table, such as to prevent anyone from putting new rows or updating rows?

Thanks, Christian

like image 308
Christian Avatar asked Sep 17 '12 12:09

Christian


1 Answers

It's not clear to me why you would want this, but if you really want to lock the whole table you could:

  • Turn off row and page locking so that everything escalates to a table lock

Example adapted from here:

ALTER INDEX [MyIndexName] ON [dbo].[MyTableName] SET ( ALLOW_ROW_LOCKS = OFF, ALLOW_PAGE_LOCKS = OFF)

Note: this assumes your application solely "owns" these tables -- wouldn't want to apply this and break some other app

  • Set your queries to use Serializable isolation level

Example adapted from here:

TransactionOptions topt = new TransactionOptions();   
topt.IsolationLevel = System.Transactions.IsolationLevel.Serializable;
using (var tran = new TransactionScope(TransactionScopeOption.Required, topt)) {
   //do stuff
}
like image 52
explunit Avatar answered Oct 23 '22 09:10

explunit