fino ad ora ho sempre usato una struttura simile per ottenere i dati dal database e compilare un DataTablecomando SQL Smaltimento e chiudendo la connessione
public static DataTable GetByID(int testID)
{
DataTable table = new DataTable();
string query = @"SELECT * FROM tbl_Test AS T WHERE T.testID = @testID";
using (SqlConnection cn = new SqlConnection(Configuration.DefaultConnectionString))
{
SqlCommand cmd = new SqlCommand(query, cn);
cmd.Parameters.Add("@testID", SqlDbType.Int).Value = testID;
cn.Open();
table.Load(cmd.ExecuteReader());
}
return table;
}
Ora ho visto alcune avvertenze per l'analisi di compilazione:
TestService. cs (37): CA2000: Microsoft.Reliability: nel metodo 'TestService.GetByID (int)', l'oggetto 'table' non è disposto lungo tutti i percorsi di eccezione. Chiama System.IDisposable.Dispose sull'oggetto 'table' prima che tutti i riferimenti siano fuori portata.
TestService.cs (42): CA2000: Microsoft.Reliability: nel metodo 'TestService.GetByID (int)', chiamare System.IDisposable.Dispose sull'oggetto 'cmd' prima che tutti i riferimenti siano fuori portata.
Devo cambiare il mio codice in
public static DataTable GetByID(int testID)
{
DataTable table = new DataTable();
string query = @"SELECT * FROM tbl_Test AS T WHERE T.testID = @testID";
using (SqlConnection cn = new SqlConnection(Configuration.DefaultConnectionString))
{
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.Add("@testID", SqlDbType.Int).Value = testID;
cn.Open();
table.Load(cmd.ExecuteReader());
}
}
return table;
}
Cosa fare con oggetto DataTable? È buona pratica inserire SqlCommand all'interno?
Grazie
Acclamazioni
Sì. Il tuo codice è corretto ora. Disponi sempre la classe di implementazione IDisposable. Ma SqlDataReader è anche usa e getta? – lnu
Disponi il DataTable che torni? – Kangkan
Credo che il lettore sia monouso sì, e forse questo è il problema WRT che la tabella non è disposta in quanto contiene un lettore che non è stato esplicitamente chiuso, sebbene mi aspetto che sia stato chiuso implicitamente quando il cmd è stato eliminato. –