views:

47

answers:

3

Say I take an arbitrary LINQ2SQL query's Expression, is it possible to invoke it somehow?

MyContext ctx1 = new MyContext("...");
var q = from t in ctx1.table1 where t.id = 1 select t;
Expression qe = q.Expression;
var res = Expression.Invoke(qe); 

This throws ArgumentException "Expression of type System.Linq.IQueryable`1[...]' cannot be invoked".

My ultimate goal is to evaluate the same query on several different data contexts.

A: 

LINQ2SQL expressions are parsed by the LINQ2QL Provider and converted into T-SQL. My guess is that exception is being raised explicitly- that Microsoft did not intend for those expressions to be Invoked directly (you could confirm this using Reflector.)

Dave Swersky
A: 

If you goal is to run an Expression across different contexts, why not create just the expression like so:-

    Expression<Func<MyClass, bool>> myExpression = x => x.id == 1;

Then you can do whatever you like with it, including using it in .Where() clauses.

Hightechrider
A query is way more than a WHERE clause. I want *arbitrary* queries.
Remus Rusanu
+1  A: 

Queries are not Expressions. A Query has an ExpressionTree.

Queries are not Methods to be invoked.

Queries may be Enumerated, yielding their results. This code will Enumerate any IQueryable:

List<object> result = query.Cast<object>().ToList();

My ultimate goal is to evaluate the same query on several different data contexts.

Then you should write your queries as query generators, that accept DataContext as a parameter.

Func<MyDataContext, IQueryable<Customer>> queryGen =
    (dc) => dc.Customers.Where(c => c.Name == "Bob");
  //now we can get some queries
IQueryable<Customer> query1 = queryGen(new MyDataContext());
IQueryable<Customer> query2 = queryGen(new MyDataContext());
David B
Are you claiming the property IQueryable.Expression does not exists? http://msdn.microsoft.com/en-us/library/system.linq.iqueryable.expression.aspx
Remus Rusanu
Accessing a query's Expression in order to tamper with the DataContext is like disassembling your car engine in order to turn on the radio.
David B