实体框架中锁定表 [英] Locking tables in Entity Framework
问题描述
有没有办法锁定整个表,例如阻止任何人新行或更新行?
谢谢,
Christian
我不明白为什么你会想要这个,但如果你真的想锁定整个表,你可以:
- 关闭行和页面锁定,使所有内容升级到表锁定
从此处:
ALTER INDEX [MyIndexName] ON [dbo]。[MyTableName] SET(ALLOW_ROW_LOCKS = OFF,ALLOW_PAGE_LOCKS = OFF)
注意:这假设您的应用程序完全拥有这些表 - 不想应用这个并打破一些其他应用程式
- 将查询设置为使用Serializable隔离级别
示例改编自这里:
TransactionOptions topt = new TransactionOptions();
topt.IsolationLevel = System.Transactions.IsolationLevel.Serializable;
using(var tran = new TransactionScope(TransactionScopeOption.Required,topt)){
// do stuff
}
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
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
}
这篇关于实体框架中锁定表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!