c# - 如何更改隔离级别?

标签 c# sql-server-2008 entity-framework transactions

我正在使用 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 EngineSET 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/

相关文章:

c# - 如何使用 context.Forward 和 autofac

c# - 方法 xx 和 yy 使用相同的 SOAPAction

sql-server - 打开 SQL Server .bak 文件(不恢复!)

sql - 在 Group By 查询中划分值

mysql - 如何连接mvc和mysql?

asp.net-mvc - ASP.NET MVC 3 EF Code First - 如何创建一个可以选择性地引用其自身类型的父级的模型?

c# - AutoMapper - 忽略所有实现的基类的属性

c# - 在 tableadapter 上执行自定义查询

sql - 如何汇总按列和日期分组的数据,并考虑丢失数据的日期

c# - CLR 类型到 EDM 类型的映射对于 EF 6 和 5 不明确?