2010-09-08 44 views
5

Tôi đang cố gắng để tạo ra một truy vấn động sử dụng cây biểu hiện trong LINQ to đại diện cho truy vấn sau đâyTạo một cây biểu hiện trong C#

WageConstIns.Where(WageConstIn => WageConstIn.Serialno.ToString().StartsWith("2800")); 

tôi đã cố gắng để tạo ra nó như vậy:

MemberExpression le1 = LinqExpression.Property(paramExp, "Serialno"); 
MethodCallExpression le2 = LinqExpression.Call(le1, typeof(string).GetMethod("ToString", System.Type.EmptyTypes)); 
ConstantExpression le3 = LinqExpression.Constant("2800"); 
MethodCallExpression le4 = LinqExpression.Call(le2, typeof(string).GetMethod("StartsWith")); 

Tôi gặp lỗi trong thời gian chạy. Làm cách nào để truy vấn trên có thể được xây dựng tốt nhất bằng cách sử dụng cây biểu thức?

+0

Tại sao bạn không cho chúng tôi biết lỗi bạn đang gặp phải? – LukeH

Trả lời

7

Cách đơn giản nhất là nên chỉ khai báo nó như một Expression<Func<...>>

public static class Program { 
    public static void Main() { 
     Expression<Func<DummyClass, Boolean>> predicate = WageConstIn => WageConstIn.Serialno.ToString().StartsWith("2800"); 
    } 
} 

Nhưng nếu bạn muốn xây dựng nó bằng cách sử Expressions khác nhau ...

public static class Program { 
    public static void Main() { 
     var param = Expression.Parameter(typeof(DummyClass), "WageConstIn"); 
     var constValue = Expression.Constant("2800"); 

     // WageConstIn => WageConstIn.Serialno.ToString().StartsWith(...) 
     var first = Expression.Lambda(
      parameters: param, 
      body: Expression.Call(
       instance: Expression.Call(
        instance: Expression.Property(param, "Serialno"), 
        methodName: "ToString", 
        typeArguments: null, 
        arguments: null 
       ), 
       methodName: "StartsWith", 
       typeArguments: null, 
       arguments: new[] { constValue } 
      ) 
     ); 

     // WageConstIn => Convert.ToString(WageConstIn.Serialno).StartsWith(...) 
     var second = Expression.Lambda(
      parameters: param, 
      body: Expression.Call(
       instance: Expression.Call(
        type: typeof(Convert), 
        methodName: "ToString", 
        typeArguments: null, 
        arguments: new[] { Expression.Property(param, "Serialno") } 
       ), 
       methodName: "StartsWith", 
       typeArguments: null, 
       arguments: new[] { constValue } 
      ) 
     ); 
    } 
} 

Hầu hết mọi người [mà tôi đã nói chuyện với] người nhập tên miền của cây biểu thức thường hài lòng với chức năng System.Linq.Dynamic. (Mà có thể được lạm dụng vào rất nhiều cách khác nhau.) Đoạn mã của sự khiếp sợ tinh khiết này là một phần của mã mẫu Visual Studio, có thể ẩn ở đâu đó trên đĩa cứng của bạn rồi.

+0

Hãy giúp với cây biểu thức cho: DummyCol.Where (DummyItem => Convert.ToString (DummyItem.Serialno) .StartsWith ("2008")) –

+0

Tôi đã thêm cây biểu thức thứ hai vào mã ví dụ. – sisve

Các vấn đề liên quan