Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing DynamicExpression with unknown types

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?

like image 634
sean Avatar asked Dec 31 '10 05:12

sean


1 Answers

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"); 
like image 158
goric Avatar answered Oct 04 '22 04:10

goric