1
我需要從我的數據庫表中刪除所有數據。所以我使用DataContext.ExecuteCommand
。使用一個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];");
}
約FK - 我發現從表中刪除數據的正確方法,當我爲獨立的服務器創建'ExecuteCommand'。我希望它能像你的例子一樣在查詢中工作? – demo
不知道爲什麼,但我得到錯誤:'解析查詢時出錯。 [令牌行號= 1,令牌行偏移量= 31,令牌出錯= DELETE]' – demo
如果'context是DataContext',使用'context.Database.ExecuteSqlCommandAsync'會更好嗎? – demo