Using unknown types in DynamicExpression

c# dynamic-linq expression-trees lambda linq


I could appreciate some assistance if someone is highly familiar with the Linq.Dynamic namespace since I couldn't locate any in-depth materials online.

I mostly use DynamicExpression. To build an expression when the type is unknown at compile time, use ParseLambda,

public Expression GetExpression(Type t, List<QueryFilter> filters)
   // pseudo code
   // extracts a string representation of the query as 'expressionString'

   return DynamicExpression.ParseLambda(t, typeof(Boolean), expressionString, values);

A QueryFilter's location:

public class QueryFilter 
    string propertyName;
    ExpressionType operationType;
    object value;

This denotes a straightforward binary function, e.g., "Age > 15."

This is how the "GetExpression" function works; it requires two types, one for input and one for output, and produces what would typically be produced by a Func delegate. Additionally, a string representing the query and a params object[] containing values, referred to above as "expressionString" and "values," respectively, are required.

However, utilizing a DataContext created by SqlMetal, I am having problems running the dynamic expression in LINQ-to-SQL (.dbmc file).

DatabaseContext db = new DatabaseContext(connectionString);

var filter = DynamicExpressionBuilder.
      GetExpression(typeof(SysEventLogT), sysEventFilters)

var query = db.SysEventLogT.Where(filter);

causes the aforementioned error


has the finest extension method overload but no definition for "Where"

System.Linq.Dynamic.DynamicQueryable.Where<T>(System.Linq.IQueryable<T>, string, params object[]) 

makes several unsupportable claims.

My DataContext instance does, in fact, treat the SQL tables as properties, so do I somehow need to reflect this with GetProperty() for this to work? Or maybe I should make another. To what extent?

12/31/2010 5:45:20 AM

Accepted Answer

The DynamicQueryable expression type is the one your GetExpression has returned. Where method anticipates a string as the first argument when used as an extension method.

You must dial Where to look as follows:

var query = db.SysEventLogT.Where("Age > @0", 15); 

To be clear, you might also try the following:

var query = db.SysEventLogT.AsQueryable().Where("Age > @0", 15); 

It should be noted that, if simpler, you may create a sting that contains the whole filter and forego using the params object[] argument entirely:

var query = db.SysEventLogT.AsQueryable().Where("Age > 15"); 
12/31/2010 1:12:17 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow