如何检查迁移中是否存在表?

时间:2017-10-02 18:39:42

标签: entity-framework ef-migrations

这和我一样接近......

public static class Helpers
{
    public static bool TableExists(this MigrationBuilder builder, string tableName)
    {
        bool exists = builder.Sql($@"SELECT 1 FROM sys.tables AS T
                     INNER JOIN sys.schemas AS S ON T.schema_id = S.schema_id
                     WHERE S.Name = 'SchemaName' AND T.Name = '{tableName}'");

        return exists;
    }

}

但是如何从SQL调用中获得结果?

3 个答案:

答案 0 :(得分:1)

这是一个解决方案......

public override void Up()
{
    if (!Exists("dbo.MyTable"))
    {
        ... do something
    }
}

private static bool Exists(string tableName)
{
    using (var context = new DbContext(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
    {
        var count = context.Database.SqlQuery<int>("SELECT COUNT(OBJECT_ID(@p0, 'U'))", tableName);

        return count.Any() && count.First() > 0;
    }
}

此查询立即运行,而不是像其他DbMigration命令一样延迟 - 但这就是它工作的原因。结果是直接知道的,因此其他命令可以根据需要排队(或不排队)。

答案 1 :(得分:1)

这不是一个完美的解决方案,但是您可以在SQL中使用IF:

Sql("IF (EXISTS(SELECT * 
         FROM INFORMATION_SCHEMA.TABLES
         WHERE TABLE_SCHEMA = 'MySchema'
         AND  TABLE_NAME = 'TableName'))
     BEGIN
           --DO SOMETHING
     END");

答案 2 :(得分:0)

这不是一个完美的解决方案,但它可以工作

扩展类:

using Microsoft.EntityFrameworkCore.Migrations;

namespace YourProject.Extensions
{
    public static class MigrationBuilderExtensions
    {
        /// <summary>
        /// Check if database exists
        /// </summary>
        /// <param name="migrationBuilder">Migration Builder</param>
        /// <param name="tableName">Name of DB Table to check</param>
        public static bool ExistsTable(this MigrationBuilder migrationBuilder, string tableName)
        {
            try
            {
                //Returns "1" as top 1 record 
                migrationBuilder.Sql($"SELECT TOP 1 1 FROM {tableName}");

                //Table exists
                return true;
            }
            catch
            {
                //Table not exists
                return false;
            }
        }
    }
}

在您的迁移代码中:

if (migrationBuilder.ExistsTable("yourtable"))
{
    migrationBuilder.CreateTable( ... )  
}