Executing DynamicExpression with unknown types

c# dynamic-linq expression-trees lambda linq

Question

If anyone is very familar with the Linq.Dynamic namespace I could use some help -- couldn't find any indepth resources on the internet.

Basically I'm using DynamicExpression.ParseLambda to create an expression where the type is not known at compile time,

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);
}

Where a QueryFilter is:

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

Which represents a simple binary function like "Age > 15" or something.

This is how the 'GetExpression' function works, it takes 2 types -- one that is the input type and one that is the output type, and ultimately generates what would normally be created with a Func delegate. It also takes a string that represents the query and a params object[] of values, which are 'expressionString' and 'values' above, respectively.

However I am having trouble executing the dynamic expression in LINQ-to-SQL, using a DataContext generated from SqlMetal (.dbmc file).

DatabaseContext db = new DatabaseContext(connectionString);

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

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

Produces the following error,

System.Data.Linq.Table<DBReporting.Linq.Data.SysEventLogT>

does not contain a definition for 'Where' and the best extension method overload

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

has some invalid arguments.

I know that my DataContext instance actually treats the sql tables as properties...do I need to reflect with GetProperty() somehow for this to work? Or perhaps I need to create another .Where extension?

Accepted Answer

Your GetExpression is returning an Expression type - the DynamicQueryable.Where method, when used as an extension method, expects a string as the first parameter.

You need your call to Where to look like this:

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

Also, you could try the following, just to be explicit:

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

Note that if easier, you can build a sting containing the full filter and not use the params object[] parameter at all:

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



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why