使用一个DataContext.ExecuteCommand对多个表执行查询

时间:2015-12-19 20:10:09

标签: sql entity-framework datacontext sql-server-ce-4

我需要从数据库中的表中删除所有数据。所以我使用DataContext.ExecuteCommand

db.ExecuteCommand("DELETE From Products");

此方法为每个表导致对数据库的新请求。我想在一个查询中清除表中的数据。但到目前为止,我所有的尝试都没有成功。

是否可以使用DataContext.ExecuteCommand从多个表中删除数据(多个SQL查询)?

        try
        {
            using (var context = new DataContext())
            {
                context.DeleteAll();
            }
        }
        catch (Exception exception)
        {
            LogHelper.Log(exception);
        }

private static void DeleteAll(this DataContext context)
        {
            var ctx = ((IObjectContextAdapter)context).ObjectContext;

            ctx.ExecuteStoreCommand("DELETE FROM [RegionProducts]; DELETE FROM [ProductTypes]; DELETE FROM [Measurements]; DELETE FROM [Sizes]; " +
                                    "DELETE FROM [Regions]; DELETE FROM [Types]; DELETE FROM [Categories]; DELETE FROM [Images] where Product_Id is not null; DELETE FROM [Products]; " +
                                    "DELETE FROM [Brands]; DELETE FROM [Images];");
        }

1 个答案:

答案 0 :(得分:1)

这将在很大程度上取决于您使用的实际数据库系统 - 但在例如SQL Server,你应该能够有多个DELETE语句 - 用分号分隔 - 像这样:

string deleteQuery = "DELETE FROM dbo.Products; DELETE FROM dbo.OtherTable; DELETE FROM dbo.YetAnotherTable;";

db.ExecuteCommand(deleteQuery);

当然,如果其他表仍引用其数据,您需要注意可能导致一次删除失败的任何可能的FK关系 - 但是应该可以在单个db.ExecuteCommand调用中执行此操作/ p>

更新:很遗憾,在您正在使用的SQL Server Compact Edition v4中,您不能在一个命令中拥有多个SQL语句 - 它不是支持的。这种方法在真正的 SQL Server中很好 - 但 在SQL Server CE 中工作