Below is my attempt at the beginnings of a reusable ado.net data access class. Please let me know of any improvements that I could make.
Thanks!
public class DataAccess : IDisposable
{
public DbProviderFactory Factory { get; set; }
public string Connection { get; set; }
public string ProviderName { get; set; }
public DataAccess()
{
Get_ConnectionString_From_AppSettings();
Get_ProviderName_From_AppSettings();
}
private void Get_ConnectionString_From_AppSettings()
{
this.Connection = ConfigurationManager.AppSettings.Get("Database");
}
private void Get_ProviderName_From_AppSettings()
{
this.ProviderName = ConfigurationManager.AppSettings.Get("DBProvider");
}
public DataTable Connection_Return_DataTable( string sql)
{
DbConnection connection = null;
try
{
DbProviderFactory factory = DbProviderFactories.GetFactory(this.ProviderName);
this.Factory = factory;
connection = Factory.CreateConnection();
connection.ConnectionString = Connection;
DataTable dt = FillDataTable(connection, sql);
return dt;
}
catch (DataException ex)
{
Debug.WriteLine(ex.ToString());
throw;
}
finally
{
connection.Close();
connection.Dispose();
}
}
private DataTable FillDataTable(DbConnection connection, string sql)
{
DbCommand command = connection.CreateCommand();
command.CommandText = sql;
command.Connection = connection;
DbDataAdapter adapter = this.Factory.CreateDataAdapter();
adapter.SelectCommand = command;
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
public void Dispose()
{
this.Factory = null;
this.Connection = null;
this.ProviderName = null;
}
}