我想在我的應用程序中實現實體框架,我應該能夠提交和手動回滾更改。實體框架使用BeginTransaction()
第一次當我執行更新語句它成功更新表,我能夠回滾更改。 這是正確的
但第二次當我執行更新語句時,它成功更新表並提交更改。所以我無法手動回滾。 這是不對的
請讓我知道它爲什麼會發生以及如何解決這個問題。
下面的代碼只是示例來重現我的問題。
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.
}
}
}
使用['TransactionScope'](http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx) –
@GertArnold是的我想過,但如何手動提交或回滾使用TransactionScope的? – ksvimal
要提交,你只需要'Complete()'一個事務範圍。如果您丟棄未完成的TS回滾。 –