Entity Framework - How to check if table exists?

后端 未结 6 2013
自闭症患者
自闭症患者 2020-12-05 18:13

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.

6条回答
  •  长情又很酷
    2020-12-05 18:39

    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.

提交回复
热议问题