【发布时间】:2015-10-30 03:56:02
【问题描述】:
我正在尝试在我的应用程序中实现实体框架,我应该能够手动提交和回滚更改。
当我第一次执行更新语句时,它成功更新了表并且我能够回滚更改。 这是正确的
但是当我第二次执行更新语句时,它成功更新了表并提交了更改。所以我无法手动回滚。 这是错误的
请告诉我为什么会这样以及如何解决这个问题。
下面的代码只是重现我的问题的示例。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;
namespace EFTest
{
public class DBOperations
{
NorthwindEntities NorthwindContext;
DbTransaction transObject;
public DBOperations()
{
}
public void ConnectDB()
{
try
{
if (NorthwindContext == null)
{
NorthwindContext = new NorthwindEntities();
if (NorthwindContext != null && NorthwindContext.Connection.State != ConnectionState.Open)
{
NorthwindContext.Connection.Open();
transObject = NorthwindContext.Connection.BeginTransaction(IsolationLevel.ReadUncommitted);
}
}
}
catch (Exception ex)
{
throw new Exception("Database Error " + ex.Message);
}
}
public int disconnect()
{
if (NorthwindContext != null && transObject != null)
{
try
{
transObject.Rollback();
}
catch (Exception)
{
}
transObject.Dispose();
NorthwindContext.Connection.Close();
NorthwindContext.Dispose();
}
return 0;
}
public void CommitTransaction()
{
if (NorthwindContext != null && transObject != null)
{
try
{
transObject.Commit();
}
catch (Exception)
{
}
}
}
public void RollbackTransaction()
{
if (NorthwindContext != null && transObject != null)
{
try
{
transObject.Rollback();
}
catch (Exception)
{
}
}
}
public int UpdateDB()
{
int _returnVal = 0;
try
{
NorthwindContext.ExecuteStoreCommand("UPDATE Orders SET OrderDate = GETDATE() WHERE OrderID = '10248'");
}
catch (Exception ex)
{
throw new Exception("Database Error " + ex.Message);
}
return _returnVal;
}
}
public class program
{
public program()
{
//Establishing the connection.
DBOperations _DBOperations = new DBOperations();
_DBOperations.ConnectDB();
//Update the datebase
_DBOperations.UpdateDB(); //Update the database but it doesn't commit the changes.
//Issue Rollback to rollback the transaction.
_DBOperations.RollbackTransaction(); //Successfully Rollbacks the database changes.
//Again Update the datebase
_DBOperations.UpdateDB(); //Update the database it commits the changes.
//Issue Rollback to rollback the transaction.
_DBOperations.RollbackTransaction(); //Rollback fails.
}
}
}
【问题讨论】:
-
@GertArnold 是的,我想过,但是如何使用 TransactionScope 手动提交或回滚?
-
要提交,你只需要
Complete()一个事务范围。如果您在未完成的情况下处置 TS,则会回滚。 -
问题:你只执行存储命令吗?
-
@GertArnold 不。我也在使用 Context.SaveChanges() 但在一种情况下,我使用 store 命令只是为了检查特定行是否锁定在表中。我是 EntityframeWork 的新手,所以我正在尝试构建最佳逻辑。我认为最好有多个上下文实例,可能是每个屏幕一个上下文。这是对的吗?如果我错了,请纠正我。
标签: c# entity-framework