ORM 框架批量刪除一直是痛點:無法透過條件批量刪除,只能寫 SQL 或執行預存程序,程式碼中出現裸 SQL 顯得醜陋。利用 C# 3.0 強大特性擴展 LINQ to SQL,實現優雅的批量刪除與更新。
引用擴展後:
ItemDataContext db = new ItemDataContext();
// 簡單條件
db.Items.Delete(item => item.CreateTime < DateTime.UtcNow.AddMonths(-1));
// 複雜條件
db.Items.Delete(item =>
item.CreateTime < DateTime.UtcNow.AddMonths(-1) ||
item.ViewCount < item.CommentCount && item.UserName != "jeffz");
3 * 3 → 9),替換變數引用為常量[CreateTime] < {0} AND [UserName] <> {1})核心在解析表達式樹,重點處理 BinaryExpression。目前不支援複雜運算 (如 item.Introduction.Length < 10 需轉 T-SQL LEN 函數)。
ItemDataContext db = new ItemDataContext();
db.Items.Update(
item => new Item
{
Introduction = item.Title + "Hello World",
ViewCount = item.ViewCount + 1,
}, // 更新方式
item => item.CommentCount > 100 // 更新條件
);
批量更新比刪除複雜,正在開發中。原始碼可下載。