2012-10-12 2 views
2

이유가 궁금합니다. 나는 오늘 아침다른 SqlConnection의 'using'절에서 SqlConnection을 열 수 없습니까?

using (SqlConnection oConn = new SqlConnection(ConnectionString)) 
{ 
    using (SqlCommand cmd = new SqlCommand("IC_Expense_InsertCycle", oConn)) 
    { 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.Parameters.AddWithValue("@PortalId", portalId); 
     cmd.Parameters.AddWithValue("@Description", description); 
     cmd.Parameters.AddWithValue("@StartDate", start); 
     cmd.Parameters.AddWithValue("@EndDate", end); 

     try 
     { 
      oConn.Open(); 
      cmd.ExecuteNonQuery(); 
     } 
     catch (SqlException ex) 
     { 
      throw ex; 

     } 
    } 
} 

//Get the new set of ExpenseCycles for binding 
ExpenseCycle cycle = new ExpenseCycle(ConnectionString); 
return cycle.GetExpenseCycles(portalId); 

// ^^ this works just fine. The GetExpenseCycles call will basically set up the structure above with using SqlConnection and using SqlCommand 

using (SqlConnection oConn = new SqlConnection(ConnectionString)) 
{ 
    using (SqlCommand cmd = new SqlCommand("IC_Expense_InsertCycle", oConn)) 
    { 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.Parameters.AddWithValue("@PortalId", portalId); 
     cmd.Parameters.AddWithValue("@Description", description); 
     cmd.Parameters.AddWithValue("@StartDate", start); 
     cmd.Parameters.AddWithValue("@EndDate", end); 

     try 
     { 
      oConn.Open(); 
      cmd.ExecuteNonQuery(); 
     } 
     catch (SqlException ex) 
     { 
      throw ex; 

     } 

     //Get the new set of ExpenseCycles for binding 
     ExpenseCycle cycle = new ExpenseCycle(ConnectionString); 
     return cycle.GetExpenseCycles(portalId); 

     //This didn't work. The INSERT statement was successful, but it was bringing back old entries, and did not include the newest one that was just inserted 
    } 
} 

하단 코드 블록은 내가 가진 것을 처음이었다이 시나리오에 달리고, 내 테스트 환경에 대한 반환 카운트는 단 1을했지만, 데이터베이스에이 개 기록이 있었다. 새로 삽입 된 레코드를 가져 오지 않았습니다.

using (SqlConnection oConn = new SqlConnection(ConnectionString)) 
{ 
    using (SqlCommand cmd = new SqlCommand("IC_Expense_GetExpenseCyclesByPortal",oConn)) 
    { 
     oConn.Open(); 
     using (SqlDataReader sdr = cmd.ExecuteReader()) 
     { 
      //Read List<expensecycle> here 
     } 
    } 
} 

어떤 아이디어 이유 :

GetExpenseCycles의 기본 코드는 다음과 같다? 예외가 발생하지 않았습니다. 던져

+0

Hrrrm, 일반적인 throw로 인해'SqlException'이 아닌 다른 것을 던질 것이라고 생각하십니까? – dgarbacz

+0

'SqlException'으로 무엇인가를하려고하지 않는다면, 그냥 다시 던지기 만하면됩니다. – James

+0

코드 내에 return 문이 있으므로 첫 번째 삽입 만 실행됩니다. –

답변

3

예외는 그렇게 오류 ... 나는 연결이 겹치지 않는 첫 번째 시나리오에서 연결

에 격리 수준을 의심하지 않습니다.

ExpenseCycle()은 연결 문자열을 사용하므로 안전하게 새 연결을 시작할 것이라고 생각할 수 있습니다. 두 번째 예에서

(문제의 경우) 연결이 겹치지 않는 :

인스턴스 커밋 읽기 분리 레벨은 상기 "클로징"연결이 아직 기록 (커밋) 새로운 안정화되지 않으면 연결은 변경 사항 (이 경우에는 삽입 항목)을 선택하지 않습니다.

가능한 솔루션 또는 것을 시도하기 : 1. 연결

1

(더 나은 연습도 이럴입니다) 2. 패스 ExpenseCycle에 대신 ConnectionString에의 연결()에 격리 수준 앰비 트랜잭션이 유효 할 수 있습니다 (코드 블록이 트랜잭션의 범위 내에서 호출되면 새로운 연결은 자동으로 해당 트랜잭션에 참여합니다.) TransactionScope class을 사용하면 해당 트랜잭션의 핸들을 가져 와서 두 번째 호출 전에 커밋 할 수 있습니다.

두 번째 호출이 명령의 usi 범위 내에있는 것 같습니다. 블록. 거기에서 외부로 이동하면 문제 다른 옵션은

bool insertSuccessful; 
using (SqlConnection oConn = new SqlConnection(ConnectionString)) 
{  
    using (SqlCommand cmd = new SqlCommand("IC_Expense_InsertCycle", oConn))  
    { 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.Parameters.AddWithValue("@PortalId", portalId); 
     cmd.Parameters.AddWithValue("@Description", description); 
     cmd.Parameters.AddWithValue("@StartDate", start); 
     cmd.Parameters.AddWithValue("@EndDate", end);   
     try 
     { 
     oConn.Open(); 
     cmd.ExecuteNonQuery(); 
     insertSuccessful=true; 
     } 
     catch (SqlException ex) 
     { 
     insertSuccessful=false 
     throw ex; 
     } 
    }//close the SqlCommand 
}//close the connection 
//Get the new set of ExpenseCycles for binding 
if(insertSuccessful) 
{ 
    ExpenseCycle cycle = new ExpenseCycle(ConnectionString); 
    return cycle.GetExpenseCycles(portalId); 
} 

내가 첫 번째 블록 생각 때문에 같이 처음 사용하는 블록으로 사용하여 외부에서 두 번째 전화를 이동하는 것입니다

using (SqlConnection oConn = new SqlConnection(ConnectionString)) 
{  
    using (SqlCommand cmd = new SqlCommand("IC_Expense_InsertCycle", oConn))  
    { 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.Parameters.AddWithValue("@PortalId", portalId); 
     cmd.Parameters.AddWithValue("@Description", description); 
     cmd.Parameters.AddWithValue("@StartDate", start); 
     cmd.Parameters.AddWithValue("@EndDate", end);   
     try 
     { 
     oConn.Open(); 
     cmd.ExecuteNonQuery(); 
     } 
     catch (SqlException ex) 
     { 
     throw ex; 
     } 
    }//close the SqlCommand 
    //Get the new set of ExpenseCycles for binding 
    ExpenseCycle cycle = new ExpenseCycle(ConnectionString); 
    return cycle.GetExpenseCycles(portalId); 
    //This might fix your problem. 
} 

를 해결하기에 충분 수도 문제를 해결해야합니다. 그렇지 않으면 두 번째 것이 분명합니다.