나는 동적 linq 및 표현 트리를 이해하려고합니다. 매우 기본적으로 열과 값을 문자열로 제공하는 equals를 수행하려고합니다. 여기 내가 지금까지 가지고있는 것입니다동적 Linq 속성 SQL로 변환
private IQueryable<tblTest> filterTest(string column, string value)
{
TestDataContext db = new TestDataContext();
// The IQueryable data to query.
IQueryable<tblTest> queryableData = db.tblTests.AsQueryable();
// Compose the expression tree that represents the parameter to the predicate.
ParameterExpression pe = Expression.Parameter(typeof(tblTest), "item");
Expression left = Expression.Property(pe, column);
Expression right = Expression.Constant(value);
Expression e1 = Expression.Equal(left, right);
MethodCallExpression whereCallExpression = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { queryableData.ElementType },
queryableData.Expression,
Expression.Lambda<Func<tblTest, bool>>(e1, new ParameterExpression[] { pe }));
// Create an executable query from the expression tree.
IQueryable<tblTest> results = queryableData.Provider.CreateQuery<tblTest>(whereCallExpression);
return results;
}
DB의 열에 잘 작동합니다. 하지만 내 코드의 속성에 실패합니다. 예 :
public partial class tblTest
{
public string name_test
{ get { return name; } }
}
오류가 발생하면 SQL로 변환 할 수 없다고 할 수 없습니다. 내가 표현 < Func로 속성을 재작 성하려고했지만 행운을 빌어, 어떻게 이러한 간단한 방법으로 linq와 함께 사용할 수 있도록 간단한 속성을 변환 할 수 있습니까?
많은 감사
감사합니다. Expression에서 간단한 작업을 SQL로 변환 할 수 있기를 바랬습니다. 예를 들어 열 등을 조인 할 때 SQL에서 가능해야하는 것들은 정렬과 필터링이 db에서 처리 될 수 있음을 의미합니다. 복잡한 시나리오는 DB에서 가능하지 않지만 기본 속성이 DB에서 처리 될 수있는 방식으로 변환되거나 구축 될 수 있기를 바랍니다. –
@Matthew - PredicateBuilder를 사용하여 복잡한 필터를 작성하는 방법을 살펴볼 수 있습니다. 이것은 제가 사용하는 것입니다 : http://www.albahari.com/nutshell/predicatebuilder.aspx – tvanfosson