I completely agree with the compiler - you need to manage your fields here or (as already noted) - do not create 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 use this type with using(...)
But! It seems 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(); } } }
source share