EF4 CTP5 - LINQ Dynamic Query Library throws InvalidCastException

杀马特。学长 韩版系。学妹 提交于 2019-12-06 04:04:51

问题


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>.



来源:https://stackoverflow.com/questions/4431869/ef4-ctp5-linq-dynamic-query-library-throws-invalidcastexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!