1
我嘗試過使用下面的代碼進行實體交易,但不幸的是, 不適用於事務回滾。請幫幫我。實體交易不起作用
public void AddAGMDate()
{
DbTransaction Transaction = null;
using (EntityConnection DatabaseConnection = new EntityConnection("name=Insta_SAEntities"))
{
try
{
if (DatabaseConnection.State == ConnectionState.Closed)
DatabaseConnection.Open();//open connection
var CurrentContext = new Insta_SAEntities(DatabaseConnection);
Transaction = CurrentContext.Connection.BeginTransaction();//begin transaction
TR_AGMDatesEntityObject objAGMDates = new TR_AGMDatesEntityObject();
objAGMDates.ClientID = Convert.ToInt64(ddlClientName.SelectedValue);
objAGMDates.AGMDate = Convert.ToDateTime(txtAGMDate.Text.Trim());
objAGMDates.CreatedBy = 0;
objAGMDates.CreatedDate = Convert.ToDateTime(System.DateTime.Now);
objAGMDates.UpdatedBy = 0;
objAGMDates.UpdatedDate = Convert.ToDateTime(System.DateTime.Now);
int result = AGMDatesBL.AddAGMDate(objAGMDates);
if (true)
{
int n1 = 10, n2 = 0;
int res = n1/n2;//Error, want transaction to rollback (for taesting)
}
Transaction.Commit();//commit transaction
if (result == 1)
{
ScriptManager.RegisterClientScriptBlock(Page, GetType(), "script", "alert('AGM Date Successfully entered ');" +
"window.location.href='ManageAGMDate.aspx';", true);
}
else if (result == 2)
{
txtAGMDate.Text = "";
ScriptManager.RegisterClientScriptBlock(Page, GetType(), "script", "alert('AGM Date Already Exist!');", true);
}
else if (result == 0)
{
ScriptManager.RegisterClientScriptBlock(Page, GetType(), "script", "alert('Unable to Add AGM Date!');" +
"window.location.href='ManageAGMDate.aspx';", true);
}
}
catch (Exception ex)
{
Transaction.Rollback();//rollback transaction
if (log.IsErrorEnabled) log.Error(string.Format("{0} ,Page URL={1}, Method Name={2} ,Error={3}", _LogMsgAdd, Request.Url.AbsoluteUri, MethodInfo.GetCurrentMethod().DeclaringType.FullName + "." + MethodInfo.GetCurrentMethod().Name, ex.Message.ToString()));
Session["error"] = ex.Message.ToString();
Response.Redirect("~/Common/Errors/ErrorPageWM.aspx?ShB=Y", false);
}
finally
{
if (DatabaseConnection != null)
{
if (DatabaseConnection.State == ConnectionState.Open)
DatabaseConnection.Close();
}
}
}
我你不使用多個數據庫/服務器或者甚至是表中看到。所以你不需要額外的事務對象。英孚照顧這一點。 因此將你的對象添加到對象集。然後在try catch塊中執行SaveChanges()。即使您擁有多個實體,它也可以將其全部或全部保存起來。 (這是EF4) 我不知道如果您使用存儲過程艱難會發生什麼 – hazimdikenli 2011-02-07 13:17:00