LINQ通用连接和实体框架

时间:2011-09-23 12:07:40

标签: c# linq entity-framework generics join

我的要求是实现一个通用的Join方法,这个方法可以IQueryable Join。

我使用了Join方法,如下所示:

public static IQueryable Join(this IQueryable outer, IEnumerable inner, string outerSelector, string innerSelector, string resultsSelector, params object[] values)
    {
        if (inner == null) throw new ArgumentNullException("inner");
        if (outerSelector == null) throw new ArgumentNullException("outerSelector");
        if (innerSelector == null) throw new ArgumentNullException("innerSelector");
        if (resultsSelector == null) throw new ArgumentNullException("resultsSelctor");

        System.Linq.Expressions.LambdaExpression outerSelectorLambda = DynamicExpression.ParseLambda(outer.ElementType, null, outerSelector, values);
        System.Linq.Expressions.LambdaExpression innerSelectorLambda = DynamicExpression.ParseLambda(inner.AsQueryable().ElementType, null, innerSelector, values);

        System.Linq.Expressions.ParameterExpression[] parameters = new System.Linq.Expressions.ParameterExpression[] {
        System.Linq.Expressions.Expression.Parameter(outer.ElementType, "outer"), System.Linq.Expressions.Expression.Parameter(inner.AsQueryable().ElementType, "inner") };
        System.Linq.Expressions.LambdaExpression resultsSelectorLambda = DynamicExpression.ParseLambda(parameters, null, resultsSelector, values);

        return outer.Provider.CreateQuery(
            System.Linq.Expressions.Expression.Call(
                typeof(Queryable), "Join",
                new Type[] 
                { 
                    outer.ElementType, 
                    inner.AsQueryable().ElementType, 
                    outerSelectorLambda.Body.Type, 

                    resultsSelectorLambda.Body.Type 
                },
                outer.Expression, 
                inner.AsQueryable().Expression, 
                System.Linq.Expressions.Expression.Quote(outerSelectorLambda), 
                System.Linq.Expressions.Expression.Quote(innerSelectorLambda), 
                System.Linq.Expressions.Expression.Quote(resultsSelectorLambda)));
    }


    //The generic overload.
    public static IQueryable<T> Join<T>(this IQueryable<T> outer, IEnumerable<T> inner, string outerSelector, string innerSelector, string resultsSelector, params object[] values)
    {
        return (IQueryable<T>)Join((IQueryable)outer, (IEnumerable)inner, outerSelector, innerSelector, resultsSelector, values);
    }

我使用了Join方法,如下所示:

       var q = Join(e1, e2, "Company_ID", "Company_ID",
        "new ( outer.Company_ID as CompanyId)"      );

但我得到的错误如下所示:

类型'System.Linq.Queryable'上没有泛型方法'Join'与提供的类型参数和参数兼容。如果方法是非泛型的,则不应提供类型参数。

请帮助。

1 个答案:

答案 0 :(得分:0)

outerSelectorLambda.Body.Type

这不应该是Body.ReturnType吗?


这个退货声明太大了。将其分解并使用调试器查看类型。