开发者

Passing delegate to CompiledQuery.Compile method

While trying to pass delegate System.Func<T,TResult> to CompiledQuery.Compile method, I am getting the following error

"Error 1 The type arguments for method 'System.Data.Linq.CompiledQuery.Compile(System.Linq.Expressions.Expression>)' cannot be inferred from the usage. Try spe开发者_JAVA技巧cifying the type arguments explicitly."

public static void CompiledLINQQuery()
{
    Northwind_LINQtoSQLDataContext objData = new Northwind_LINQtoSQLDataContext();
    Func<Northwind_LINQtoSQLDataContext, IQueryable<Customer>> LINQHolder = GetPreCompiledQuery;

    LINQHolder = CompiledQuery.Compile(LINQHolder); //This is where the error comes up           
    var Results = LINQHolder.Invoke(objData);   
}

private static IQueryable<Customer> GetPreCompiledQuery(Northwind_LINQtoSQLDataContext objD)
{
    return from cust in objD.Customers where cust.Country == "Germany" select cust;
}

at the same time, if I pass the LINQ directly to the CompiledQuery.Compile method, then it works without any errors.

LINQHolder = CompiledQuery.Compile((Northwind_LINQtoSQLDataContext objD) => from cust in objD.Customers where cust.Country == "Germany" select cust);

I dont understand why I am not able to pass a delegate instead of the LINQ query expression.

Please help me to resolve this.


CompiledQuery.Compile() is only defined on Expression<Func<>>, but not on Func<>

Does your code compile if you re-write the statement as

var LINQHolder = GetPreCompiledQuery;
var CompiledLINQHolder = CompiledQuery.Compile(LINQHolder); 

?


You're not able to pass a delegate because the method signature specifies an expression tree, not a delegate - it's as simple as that. They are two very different sets of types.

What they have in common - and the reason your final piece of code will compile - is that the compiler can convert a lambda expression into either a delegate or an expression tree. Now that's not how you're creating the delegate in the first case - you're actually using a method group conversion. That's never going to create an expression tree.

If you want to specify your query in a separate method, it will have to be something like this:

private static Expression<Func<Northwind_LINQtoSQLDataContext,
                               IQueryable<Customer>>
    GetPreCompiledQuery()
{
    return db => from cust in db.Customers 
                 where cust.Country == "Germany"
                 select cust;
}

By the way, it's worth being aware that for simple queries, query expressions are often more cumbersome than using the extension methods. For example, the above is equivalent to:

private static Expression<Func<Northwind_LINQtoSQLDataContext,
                               IQueryable<Customer>>
    GetPreCompiledQuery()
{
    return db => db.Customers.Where(cust => cust.Country == "Germany");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜