EF4 CTP5 - LINQ Dynamic Query Library throws Inval

2019-04-10 01:27发布

问题:

With the upgrade to EF4 CTP5, the previously working (with CTP4) LINQ Dynamic Query Library throws the following exception

Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery' to type 'System.Linq.IQueryable`1[KIT.TAM.Core.Entities.TravelAgent]'.

on the return statement below:

namespace System.Linq.Dynamic
{
    public static class DynamicQueryable
    {
        public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object[] values)
        {
            return (IQueryable<T>)Where((IQueryable)source, predicate, values);
        }
    }
}

Is there an updated version of the library that works with EF4 CTP5?

Thanks folks.

回答1:

Solved this one. In DynamicLibrary.cs:

I replaced

public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object[] values)
{    
    return (IQueryable<T>)Where((IQueryable)source, predicate, values);
}

with

public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object[] values)
{
    if (source == null) throw new ArgumentNullException("source");
    if (predicate == null) throw new ArgumentNullException("predicate");
    LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, typeof(bool), predicate, values);
    return source.Provider.CreateQuery<T>(
        Expression.Call(
            typeof(Queryable), "Where",
            new Type[] { source.ElementType },
            source.Expression, Expression.Quote(lambda)));
}

This is the basically the same code in

public static IQueryable Where(this IQueryable source, string predicate, params object[] values)

but changed source.Provider.CreateQuery() to source.Provider.CreateQuery<T>.

You will also have to do this for the static method OrderBy<T>.