Tôi đang cố gắng để tạo ra một truy vấn động sử dụng cây biểu thức để phù hợp với tuyên bố sau:Sử dụng Chọn phương pháp cho các truy vấn năng động và cây biểu
var items = data.Where(i => i.CoverageType == 2).Select(i => i.LimitSelected);
tôi có thể tạo ra các phương pháp ở đâu và có được một kết quả từ nó; tuy nhiên, tôi không thể tạo phương thức chọn.
Đây là nơi phương pháp của tôi:
var parm = Expression.Parameter(typeof(BaseClassData), "baseCoverage");
var queryData = data.AsQueryable();
var left = Expression.Property(parm, "CoverageType");
var right = Expression.Constant(2m);
var e1 = Expression.Equal(left, right);
var whereMethod = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { queryData.ElementType },
queryData.Expression,
Expression.Lambda<Func<BaseClassData, bool>>(e1, new ParameterExpression[] { parm }));
Đây là những gì tôi đang sử dụng cho phương pháp chọn:
var selectParm = Expression.Property(parm, "LimitSelected");
var selectMethod = Expression.Call(
typeof(Enumerable),
"Select",
new Type[]{typeof(BaseClassData), typeof(decimal)},
whereMethod,
Expression.Lambda<Func<BaseClassData, decimal>>(selectParm, new ParameterExpression[]{ parm})
);
Khi tôi chạy đoạn code tôi nhận được lỗi này:
No generic method 'Select' on type 'System.Linq.Enumerable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.
Tôi cũng đã thử thay đổi Enumerable thành Queryable và tôi nhận được cùng một lỗi.
'Select' và' Where' take ** two ** generic parameters. – SLaks
Bạn có nghĩa là trong mảng ParameterExpression? Tôi hỏi vì câu lệnh này hoạt động tốt như được mã hóa. Nếu tôi chỉ tạo truy vấn bằng phương thức where, mọi thứ sẽ hoạt động tốt. Đó là khi tôi cố gắng thêm phương thức chọn vào cây biểu thức. – MarkSalow
Tôi đã thêm typeof (BaseClassData) vào mảng kiểu của selectMethod và nó hoạt động. – MarkSalow