我正在使用 EF 4.0,并且我想使用隔离级别 serializable
,因为在事务中我想在读取时阻止寄存器。
好吧,在 SQL Server 中,我尝试使用以下命令更改隔离级别:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
在 C# 中,我使用这段代码来尝试阻止寄存器:
using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.Serializable }))
{
Entities myContext = new Entities();
string colors = "select * from Colors where IDColor = 2";
Colors myColor = myContext.Colors.SqlQuery(colors).FirstOrDefault<Colors>();
myColor.Color = "Red";
myContext.SaveChanges();
scope.Complete();
}
如果我逐行执行我的代码,如果我得到 SaveChanges
但仍然没有执行,例如,如果我使用 SQL Server Management Studio 查询表颜色,我可以得到记录。
然后,如果我执行保存更改并获得 scope.Clompete()
,如果我尝试使用 Management Studio 查询,我什么也得不到,因为寄存器被阻止,所以当我完成我的 C# 代码,寄存器被释放,我在 Management Studio 中得到结果。
所以我的问题是,如何在 C# 中使用可序列化隔离级别?我做错了什么吗?
P.S.:我注意到如果我使用这个命令:
DBCC useroptions;
我看到隔离级别是 serializable
,但是如果我关闭 Management Studio 并再次连接,我看到隔离级别是默认的 readCommitted
。
所以我的问题是如何为我的数据库设置默认隔离级别。
最佳答案
默认 EF 事务隔离级别基于所使用的数据库提供程序。
ef 代码中未指定的隔离级别应导致数据库服务器采用默认隔离级别。
在 SQL Server 中,默认隔离级别是 READ COMMITED。
因此您不需要在 EF 代码上指定 IsolationLevel。如果您在数据库端设置它,它也将 EF 的默认 IsolationLevel 也作为。
如何更改数据库检查的隔离级别 Isolation Levels in the Database Engine和 SET TRANSACTION ISOLATION LEVEL (Transact-SQL)
更新
要更改隔离级别
,请在 SSMS 上运行下面提到的命令:
USE YourDatabaseName;
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
检查是否应用?
USE YourDatabaseName;
GO
DBCC useroptions
MSDN 说:
Only one of the isolation level options can be set at a time, and it remains set for that connection until it is explicitly changed. All read operations performed within the transaction operate under the rules for the specified isolation level unless a table hint in the FROM clause of a statement specifies different locking or versioning behavior for a table.
希望对您有所帮助。
关于c# - 如何更改隔离级别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14536805/