扩展方法没有显示出来

时间:2014-05-07 03:54:45

标签: c# asp.net-mvc-4 extension-methods

我需要有关如何在我的ASP.Net MVC控制器中显示我的第二个扩展方法“OrderBy”(如下所示)的帮助。

第一种扩展方法“Where”显示但不显示“OrderBy”。我需要做些什么才能让它出现?或者我的代码在第二种扩展方法中是错误的?

注意:我已经通过添加:

在我的控制器中导入了命名空间
using MyApplication.Models;

这是扩展方法的代码:

namespace MyApplication.Models
{
    public static class ExtensionMethods
    {
        public static IQueryable<T> Where<T>(this IQueryable<T> source, string     columnName, string value, string filterType)
        {

        ParameterExpression table = Expression.Parameter(typeof(T), "x");
        MemberExpression column = Expression.PropertyOrField(table, columnName);
        Expression valueExpression = null;
        Expression where = null;

        if (column.Type.FullName.Contains("String")) {...}
        if (column.Type.FullName.Contains("Int32")) {...}
        if (column.Type.FullName.Contains("DateTime")){...}

        var predicate = Expression.Lambda<Func<T, bool>>(where, table);

        return source.Where(predicate);
        }

        public static IOrderedQueryable<T> OrderBy<T,TKey>(this IQueryable<T> source,   string columnName)
        {
            ParameterExpression table = Expression.Parameter(typeof(T), "x");
            Expression column = Expression.PropertyOrField(table, columnName);
            var keySelector = Expression.Lambda<Func<T, TKey>>(column,table);
            return source.OrderBy(keySelector);
        }
    }
}

这是Controller中的代码:

using MyApplication.Models;

...

using (MyContext context = new MyContext())
{

    IQueryable<Shipper> query = context.Shippers;
    query = query.Where(property,value,filterType);
    query = query.OrderBy(property);
}

非常感谢任何帮助。

-Mark


修改

这是我的新OrderBy扩展方法:

public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string columnName, bool asc)
    {
        var entityType = typeof(T);
        var property = entityType.GetProperty(columnName);
        ParameterExpression table = Expression.Parameter(entityType, "x");
        Expression column = Expression.PropertyOrField(table, columnName);

        string sortMethod="";

        if (asc) { sortMethod = "OrderBy"; }
        else { sortMethod = "OrderByDescending"; }

        var keySelector = Expression.Lambda(column,table);

        MethodCallExpression resultExp = Expression.Call(
            typeof(Queryable),
            sortMethod,
            new Type[] { entityType, property.PropertyType },
            source.Expression,
            Expression.Quote(keySelector));

        return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(resultExp);
    }

1 个答案:

答案 0 :(得分:3)

问题是你的扩展方法有两个类型参数,但编译器只能在其中一个类型推断中使用 - TKey在普通参数列表中根本没有提到,这就是什么用于类型推断。

我怀疑这会找到你的扩展方法:

// Of course I don't know that it's meant to be string. You should use whatever
// type is appropriate.
query = query.OrderBy<Shipper, string>(property);

这在使用方面可能并不理想,但至少它会引导你朝着正确的方向发展它的原因。如果你想依赖类型推断,你需要摆脱TKey作为一个类型参数,而不是通过反射来计算 - 然后执行其余的逻辑。

相关问题