我很好奇這是爲什麼。我就遇到了這個情況今天早些時候SqlConnection不能在另一個SqlConnection的'using'子句中打開嗎?
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,但有2條記錄在數據庫中。它沒有獲取新插入的記錄。
GetExpenseCycles的基本代碼如下:
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
}
}
}
任何想法,爲什麼?沒有例外拋出。
Hrrrm,你認爲只是有一個通用的拋出會拋出別的不是'SqlException'? – dgarbacz
除非你打算用'SqlException'做一些事情,否則我不會費心去重新拋出它。 – James
你在代碼中有一個return語句,所以很明顯只有第一個插入被執行 –