傳統 ORM 框架要求開發者遵循嚴格的對應規則(如存儲過程必須回傳固定欄位),一旦實際資料庫邏輯複雜(如依參數動態決定回傳欄位、或依內部旗標回傳不同結構),ORM 便難以應對,開發者往往退而求其次使用 DataTable。.NET 4.0 引入的 dynamic 關鍵字提供了新思路:若存儲過程名稱、參數、回傳物件結構皆在執行期決定,將極大提升彈性。
Using con As New SqlClient.SqlConnection(connectionString)
Dim customer = con.CallSingleProc.CustomerSelect(AccountKey:=12345)
Console.WriteLine(customer.FirstName & " " & customer.LastName)
Dim orders As IList = con.CallListProc.OrderSearch(AccountKey:=12345, MinCreatedDate:=Now.AddDays(-7), MaxCreatedDate:=Now)
Dim totalValue = Aggregate order In orders Into Sum(CDec(order.TotalOrderValue))
Console.WriteLine("This customer ordered a total of $" & totalValue & " last week")
For Each order In orders
Console.WriteLine(vbTab & "Order Key: " & order.OrderKey & " Value: $" & order.TotalOrderValue)
Next
End Using
using (var con = new SqlConnection(connectionString))
{
var customer = con.CallSingleProc().CustomerSelect(AccountKey: 12345);
Console.WriteLine(customer.FirstName + " " + customer.LastName);
IList<dynamic> orders = con.CallListProc().OrderSearch(AccountKey: 12345, MinCreatedDate: DateTime.Now.AddDays(-7), MaxCreatedDate: DateTime.Now);
var totalValue = orders.Sum(order => (decimal)order.TotalOrderValue);
Console.WriteLine("This customer ordered a total of $" + totalValue + " last week");
foreach (var order in orders)
{
Console.WriteLine("\tOrder Key: " + order.OrderKey + " Value: $" + order.TotalOrderValue);
}
}
Option Strict,C# 大量運用 dynamic,兩者語法風格自然。這個微型 ORM 專為「不符合標準 ORM 假設」的既有資料庫而生,讓開發者在保有強型別語法便利的同時,享受動態結構的自由度。