當查詢條件在編譯時期無法確定(如使用者動態勾選篩選條件),需透過運算式樹在執行期動態建構 LINQ 查詢。
IQueryable<T> 查詢編譯為運算式樹,由 Provider 轉譯為 SQLExpression<TDelegate> 代表強型別運算式樹System.Linq.Expressions 命名空間提供手動建構 API// 1. 參數運算式:Customer c
ParameterExpression param = Expression.Parameter(typeof(Customer), "c");
// 2. 屬性存取:c.ContactName
Expression selector = Expression.Property(param, typeof(Customer).GetProperty("ContactName"));
// 3. Lambda:c => c.ContactName
Expression pred = Expression.Lambda(selector, param);
// 4. 呼叫 Queryable.Select:Select(c => c.ContactName)
Expression expr = Expression.Call(
typeof(Queryable), "Select",
new Type[] { typeof(Customer), typeof(string) },
Expression.Constant(custs), pred);
// 5. 建立動態查詢並取得 SQL
IQueryable<string> query = db.Customers.AsQueryable().Provider.CreateQuery<string>(expr);
DbCommand cmd = db.GetCommand(query);
Console.WriteLine(cmd.CommandText);
// 輸出:SELECT [t0].[ContactName] FROM [dbo].[Customers] AS [t0]
雖程式碼較冗長,但提供極大彈性,是進階 LINQ 開發必備技能。