Entity framework 如何检查迁移中是否存在表?
这是我最接近的Entity framework 如何检查迁移中是否存在表?,entity-framework,entity-framework-migrations,Entity Framework,Entity Framework 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.s
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;
}
}
public override void Up()
{
如果(!存在(“dbo.MyTable”))
{
…做点什么
}
}
存在私有静态bool(字符串tableName)
{
使用(var context=new DbContext(ConfigurationManager.ConnectionString[“DefaultConnection”].ConnectionString))
{
var count=context.Database.SqlQuery(“选择count(OBJECT_ID(@p0,'U'))”,tableName);
返回count.Any()&&count.First()>0;
}
}
此查询立即运行,而不像其他DbMigration命令那样被延迟—但这就是它工作的原因。结果马上就知道了,因此其他命令可以根据需要排队(或不排队)。这不是一个完美的解决方案,但您可以在SQL中使用IF:
builder.Sql(@"
IF (EXISTS(SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'MySchema'
AND TABLE_NAME = 'TableName'))
BEGIN
--DO SOMETHING
END
");
我也一直在想办法。但是如果没有大量的工作,这似乎是不可能的。@leen3o我用SQL创建了表。我也在想同样的事情。有人有解决办法吗?