我在.NET MVC应用程序中使用Dynamic Linq Library来查询SQL Server数据库。到目前为止一切正常。
我需要进行动态选择但总是返回类型的表达式' T'预期:
public static IQueryable<T> SelectByFields<T>(this IQueryable<T> q, string expression, params object[] values) // IEnumerable<string> fieldNames)
{
try
{
var param = Expression.Parameter(typeof(T), "p");
var lambda = System.Linq.Dynamic.DynamicExpression.ParseLambda(new ParameterExpression[] { param }, typeof(T), expression, values);
Type[] types = new Type[] { q.ElementType, lambda.Body.Type };
return q.Provider.CreateQuery<T>(Expression.Call(typeof(Queryable), "Select", types, q.Expression, Expression.Quote(lambda)));
}
catch
{
return q;
}
答案 0 :(得分:0)
最后我解决了问题
public static IQueryable SelectByFields(this IQueryable q, string expression, params object[] values) // IEnumerable<string> fieldNames)
{
try
{
if (q == null)
throw new ArgumentNullException("source");
if (expression == null)
throw new ArgumentNullException("selector");
LambdaExpression lambda = System.Linq.Dynamic.DynamicExpression.ParseLambda(q.ElementType, null, expression, values);
Type[] types = new Type[] { q.ElementType, lambda.Body.Type };
return q.Provider.CreateQuery(Expression.Call(typeof(Queryable), "Select", types, q.Expression, Expression.Quote(lambda)));
}
catch
{
return q;
}
}
并致电方法
var aux = context.CLIENTES.SelectByFields("new (ID)") as IQueryable<Object>;