'Entity Framework - How to check if table exists?
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.
I want to check if a special table (entity) is existing or not. Is it possible with an framework implementation or do I need to write custom methods? If I need to write my own implementation, what would be the most generic approach to do that?
Thanks for any help.
Solution 1:[1]
I can't add comment to previous post. I'm using SQL Compact and I don't know schema of the table. I'm using this code to check for table It's pretty the same that in previous post but It works for any table.
/// <summary>
/// Check if data table is exist in application
/// </summary>
/// <typeparam name="T">Class of data table to check</typeparam>
/// <param name="db">DB Object</param>
public static bool CheckTableExists<T>(this ModelLocker db) where T : class
{
try
{
db.Set<T>().Count();
return true;
}
catch (Exception)
{
return false;
}
}
Solution 2:[2]
An alternative method; it's not as efficient as Ladislav's, but it's not tied to SQL Server (edited to add Where clause to address performance issue):
bool CheckTableExists()
{
try
{
context.YourTable.Where(s => s.<yourKeyField> = <impossible value>).Count();
return true;
}
catch (Exception)
{
return false;
}
}
Solution 3:[3]
Assumption: SQL Server
Catching any old exception when querying the DbSet does not mean the table does not exist.
Querying a DbSet where the table does not exist will throw an EntityCommandExecutionException with an inner exception of type SqlException. That inner exception has an ErrorNumber property.
Error number 208 reads (source):
Invalid object name '%.*ls'.
Solution 4:[4]
I think following code is a little bit more understandable.
using(YourDbEntities db = new YourDbEntities())
{
bool IsExists = db.Database
.SqlQuery <int?> (@"
SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = '" + yourTableName + "'
")
.FirstOrDefault() > 0;
return IsExists;
}
Solution 5:[5]
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<int>(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.
Solution 6:[6]
this code create all tables automatic if dose not exist
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var x = modelBuilder.RegisterEntityType;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Aaron Hudon |
| Solution 4 | Ali Soltani |
| Solution 5 | |
| Solution 6 | Mohammed |
