【问题标题】:How to check if table exists in a migration?如何检查表是否存在于迁移中?
【发布时间】:2020-03-12 04:54:14
【问题描述】:

这是我所知道的最接近的......

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

【问题讨论】:

  • 我也一直在尝试解决这个问题。但是,如果没有大量的工作,这似乎是不可能的。
  • @leen3o 我用 SQL 创建了表。
  • 我也在想同样的事情。谁有解决办法?

标签: entity-framework entity-framework-migrations


【解决方案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 命令那样被延迟 - 但这就是它起作用的原因。结果马上就知道了,以便其他命令可以根据需要排队(或不排队)。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      • 2019-06-08
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2010-12-23
      相关资源
      最近更新 更多