使用LINQ to SQL時,難免會遇到基於簡潔效率考量需要直接下SQL指令的場合。依我的習慣,遇到這類情境我就不用LINQ寫法硬幹了。DataContext物件提供了ExecuteCommand及ExecuteQuery兩個方法,可以直接撰寫有效率的SQL語法,交給DB執行批次更新動作或取回複合式查詢的結果。
public static void Test3()
{ using (MyLabDataClassesDataContext db =
new MyLabDataClassesDataContext())
{ db.Log = Console.Out;
db.ExecuteCommand(@"
UPDATE HumanResources.Employee
SET Title = {0}WHERE EmployeeID = {1}AND BirthDate = {2}", "Jedi Master",
1,
new DateTime(1972, 5, 15)
);
Console.Read();
}
}
查詢時的處理方法也差不多,但ExecuteQuyer必須指定查詢結果要對應的物件型別,如果查詢結果來自JOIN或有另外組合欄位的話,就沒有現成的物件型別可用,要自行定義物件來承接查詢結果。如以下範例:
class ResultClass
{ public int EmployeeId { get; set; } public string Title { get; set; }}
public static void Test4()
{
using (MyLabDataClassesDataContext db =
new MyLabDataClassesDataContext())
{ db.Log = Console.Out;
var q = db.ExecuteQuery<ResultClass>(@"
SELECT EmployeeID,Title
FROM HumanResources.Employee
WHERE Title LIKE '%' + {0} + '%'", "Manager");
foreach (ResultClass x in q)
{ Console.WriteLine("{0}-{1}", x.EmployeeId,
x.Title
);
}
Console.Read();
}
}