I\'m using the Entity Framework with Code First approach. The base class DbContext has functions to create and delete the database as well as to check for its existence.
In EF Core, I have added the TableExists method as a extension method for the DbContext class. Here is my solution using Dapper.
using System.Linq;
using Dapper;
using Microsoft.EntityFrameworkCore;
public static class DbContextsExtensions
{
public static bool TableExists(this DbContext dbContext, string tableName)
{
var sqlQ = $"SELECT COUNT(*) as Count FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{tableName}'";
var conn = dbContext.Database.GetDbConnection();
{
if (conn != null)
{
// Query - method extension provided by Dapper library
var count = conn.Query(sqlQ).FirstOrDefault();
return (count > 0);
}
}
return false;
}
}
And here is an usage example:
if(context != null && context.TableExists("AppSettings"))
{
// do something;
}
Hope this help other people.