Dynamic Linq Property Converting to Sql
Posted
by Matthew Hood
on Stack Overflow
See other posts from Stack Overflow
or by Matthew Hood
Published on 2010-04-13T11:50:15Z
Indexed on
2010/04/13
11:52 UTC
Read the original article
Hit count: 398
I am trying to understand dynamic linq and expression trees. Very basically trying to do an equals supplying the column and value as strings. Here is what I have so far
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;
}
That works fine for columns in the DB. But fails for properties in my code eg
public partial class tblTest
{
public string name_test
{ get { return name; } }
}
Giving an error cannot be that it cannot be converted into SQL. I have tried rewriting the property as a Expression<Func but with no luck, how can I convert simple properties so they can be used with linq in this dynamic way?
Many Thanks
© Stack Overflow or respective owner