【发布时间】:2015-08-17 02:48:23
【问题描述】:
在为数据库创建前端时遇到问题。我从数据库中的 EF6 Code First 开始。我创建了控制器并在创建页面上运行测试,但遇到了一个大问题。它给了我以下错误:
System.Data.SqlClient.SqlException: Transaction failed in database 'DB' because the statement was run under snapshot isolation but the transaction did not start in snapshot isolation. You cannot change the isolation level of the transaction to snapshot after the transaction has started unless the transaction was originally started under snapshot isolation level.
显示的另一件事是来自控制器的代码:
if (ModelState.IsValid)
{
db.Characters.Add(character);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
它突出显示了等待 db.SaveChangesAsync();作为错误线。所以现在我很困惑在哪里可以更改 MVC 代码中的事务级别。是 Web.config、为数据库创建的模型还是控制器?我知道我必须使用 TransactionScope 来更改它。
更容易将默认事务范围更改为数据库的设置。只是不确定在哪里进行更改?
【问题讨论】:
-
db在哪里被实例化,你应该在使用db上下文时使用using语句。 -
你应该在你的控制器里放什么?
-
所以我应该把它放在我拥有的控制器中: private DBModel db = new DBModel(); ?这应该在新的 DBModel 中使用(使用 TransactionScopeOption.IsolationLevel.Snapshot )?
-
不要将
DBModel设为私有,请参阅以下文章msdn.microsoft.com/en-us/data/jj729737.aspx中的Lifetime部分
标签: c# asp.net-mvc sql-server-2014 snapshot-isolation