I fully agree with the compiler - you need to dispose your fields here, or (as already noted) - not make them fields in the first place:
class DBConnectivity : IDisposable // caveat! read below first
{
public void Dispose() {
if(connection != null) { connection.Dispose(); connection = null; }
if(command != null) { command.Dispose(); command = null; }
if(dataReader != null) { dataReader.Dispose(); dataReader = null; }
}
Note that you would then use this type via using(...)
However! It looks like a static method would be more appropriate:
static class DBConnectivity
{
public static List<MasterTableAttributes> GetMasterTableList()
{
var connectionString = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
using(var connection = new SqlConnection(connectionString))
{
connection.Open();
const string masterSelectQuery = "SELECT * FROM MASTER_TABLE";
using(var command = new SqlCommand(masterSelectQuery, connection))
using(var dataReader = command.ExecuteReader())
{
var masterTableList = new List<MasterTableAttributes>();
while (dataReader.Read())
{
MasterTableAttributes masterTableAttribute = new MasterTableAttributes()
{
fileId = Convert.ToInt32(dataReader["Id"]),
fileName = Convert.ToString(dataReader["FileName"]),
frequency = Convert.ToString(dataReader["Frequency"]),
scheduledTime = Convert.ToString(dataReader["Scheduled_Time"])
};
masterTableList.Add(masterTableAttribute);
}
return masterTableList;
}
}
}
}
or perhaps simpler with a tool like "dapper":
static class DBConnectivity
{
public static List<MasterTableAttributes> GetMasterTableList()
{
var connectionString = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
using(var connection = new SqlConnection(connectionString))
{
connection.Open();
const string sql = "SELECT Id as [FileId], FileName, Frequency, Scheduled_Time as [ScheduledTime] FROM MASTER_TABLE";
return connection.Query<MasterTableAttributes>(sql).ToList();
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…