我得到,我們可以使用using
在sqlconnection
有多個命令。返回多個sqlcommands
像這樣:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command1 = new SqlCommand(commandText1, connection))
{
}
using (SqlCommand command2 = new SqlCommand(commandText2, connection))
{
}
// etc
}
然而,如果該using
是在返回讀者投的方法?
像這樣:
public IEnumerable<LocationInfo> GetData()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
{
//connection.Close();
connection.Open();
using (SqlCommand command = new SqlCommand(@"SELECT .... ", connection))
{
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
{ connection.Open(); }
using (var reader = command.ExecuteReader())
{
return reader.Cast<IDataRecord>().Select(x => new LocationInfo()
{
Names = x.GetString(2),
Values = Math.Round(x.GetDouble(7), 2).ToString("#,##0.00"),
ValuesDouble = x.GetDouble(7),
Values2 = Math.Round(x.GetDecimal(9), 2).ToString("#,##0.00"),
ValuesDouble2 = x.GetDecimal(9),
truckDelivery=x.GetDecimal(3),
truckIdle = x.GetDecimal(4),
truckRepair = x.GetDecimal(5),
truckReady = x.GetDecimal(6),
presentEmp=x.GetInt32(11),
absentEmp = x.GetInt32(12),
ondutyEmp = x.GetInt32(13),
}).ToList();
}
/* I tried this but it just got ignored
using (var reader2 = command.ExecuteReader())
{
reader2.NextResult();
return reader2.Cast<IDataRecord>().Select(x => new LocationInfo()
{
SumVol = x.GetString(0)
}).ToList();
}*/
}
}
}
請幫助我。我的第二個using
一直被忽視,不要認爲我知道什麼,因爲我是新手。先謝謝你。
您錯過了對reader.Read()的調用。目前還不清楚這個代碼是僅僅在記錄還是一組記錄中檢索。在後一種情況下,你需要一個循環 – Steve
除了Steve的建議,第二個'using'被忽略,因爲在第一個'using'塊中有一個'return',這可能是這個對象從返回的原因第一個'using'塊和下面的代碼被忽略。 – Aamir
它正在做一個從數據庫中檢索數據的循環,並且也用於像這樣的值控制器:public class ValuesController:ApiController { LocationInfoRepository objRepo = new LocationInfoRepository(); // GET api/values public IEnumerable Get() { return objRepo.GetData(); } }我知道第二個使用無知的原因是因爲return語句,我如何修改它以便我修復它。謝謝你的幫助@Steve –
MVCNoob