Is there an way using ADO.NET to determine if a table exists in a database that works with any data provider?
I’m currently doing something like this:
bool DoesTableExist(string tableName)
{
DbCommand command = this.dbConnection.CreateCommand();
command.CommandText = "SELECT 1 FROM " + tableName;
try
{
using (DbDataReader reader = command.ExecuteReader())
{
return true;
}
}
catch (DbException)
{
return false;
}
}
I’m hoping that there is a way that doesn’t involve catching exceptions.
Well, you can use the
Connection.GetSchema("TABLES")method.This returns a
DataTablewhich will contains rows of all the tables in your DB. From here you can check against this and see if the table exists.This can then be taken a step further:
If you’re using .NET 3.5, then you can make this an extension method as well.