实体框架中锁定表 [英] Locking tables in Entity Framework

查看:83
本文介绍了实体框架中锁定表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SQL数据库,我想要锁定一个表。我正在使用实体框架。基本上,有许多进程都要同时写入数据库。他们中的每一个都想更新某些表中的一行。但是,我只想要其中一个能够同时执行此操作。



有没有办法锁定整个表,例如阻止任何人新行或更新行?



谢谢,
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆