2014-07-17 71 views
-2
try 
{ 
    sqlTran = conn.BeginTransaction(); 
    String tblAuto = "Select * from tblAuto_Num where Company_Code='Comp'AND Module='WSS' AND Sub_Module='SVS' AND Doc_Type='ORD'; "; 
    SqlCommand cmd = new SqlCommand(tblAuto, conn); 
    SqlDataReader reader = cmd.ExecuteReader(); 

    while (reader.Read()) 
    { 
    }   

    reader.Close(); 
    Label1.Text = "ttt"; 
    sqlTran.Commit(); 

    conn.Close(); 
} 
catch (Exception ex) 
{ 
    if (sqlTran != null) sqlTran.Rollback(); 
    Label1.Text = ex.toString(); 
} 

當我執行SqlDataReader reader = cmd.ExecuteReader();時,它進入catch塊。誰能解釋爲什麼?執行'閱讀器'去捕捉塊

這是錯誤消息:

System.InvalidOperationException: ExecuteReader requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized. 
at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) 
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) 
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) 
at System.Data.SqlClient.SqlCommand.ExecuteReader() at TicketApp.Default.ButtonAppointment_Click(Object sender, EventArgs e) 
in c:\Users\Farhad\Documents\Visual Studio 2013\Projects\TicketApp\TicketApp\Default.aspx.cs:line 29 
+1

它拋出一個異常或東西?你調試了你的代碼嗎? –

+2

您如何使用調試器查看正在拋出的異常? – Dirk

+0

你沒有做任何事情,所以你看不出有什麼問題。記錄異常 - 或者至少在調試器中查看它。這很可能解釋它。 –

回答

2

使用使用代替在try..catchIDisposable工作:

using (var sqlTran = conn.BeginTransaction()) { 
    // Format out SQL to be more readable 
    String tblAuto = 
    @"select * 
     from tblAuto_Num 
     where Company_Code = 'Comp' and 
      Module = 'WSS' and 
      Sub_Module = 'SVS' and 
      Doc_Type='ORD'; "; 

    try { 
    using (SqlCommand cmd = new SqlCommand(tblAuto, conn)) { 
     cmd.Transaction = sqlTran; // <- Do not forget this 

     using (SqlDataReader reader = cmd.ExecuteReader()) { 
     while (reader.Read()) { 
      ... 
     } 
     } 
    } 

    sqlTran.Commit(); 
    } 
    catch (Exception) { 
    try { 
     sqlTran.Rollback(); 
     Label1.Text = "bbb"; 

     throw; // <- When catch Exception (base class) do not forget to throw 
    } 
    catch (Exception) { 
     // when rollback can't be performed 
     throw; 
    } 
    } 
} 
+0

Thankank先生德米特里爲了一個有效的答案:) – Farhad

+0

如果我不刪除'sqlTran.Rollback(); throw;'這兩行, 'This SqlTransaction has completed;它不再可用。「出現錯誤。我如何避免它? – Farhad

+0

@Farhad:http://stackoverflow.com/questions/15293673/sqltransaction-has-completed-error –