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

问题描述 投票:8回答:2

距离我已经近...

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调用中得到结果?

entity-framework ef-migrations
2个回答
3
投票
这里是一种解决方案...

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; } }


2
投票
这不是一个完美的解决方案,但是您可以在SQL中使用IF:
© www.soinside.com 2019 - 2024. All rights reserved.