如何检查迁移中是否存在表? [英] How to check if table exists in a migration?
本文介绍了如何检查迁移中是否存在表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我所能得到的最接近的了...
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调用中获得结果?
推荐答案
这里有一个解决方案...
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命令那样延迟运行--但这就是它工作的原因。结果立即可知,以便可以根据需要对其他命令进行排队(或不排队)。
这篇关于如何检查迁移中是否存在表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文