我想从带有LINQ的表中选择列名 基本上我想从列名
的表中只选择单列记录这是我到目前为止使用的
public static IQueryable<T> SelectByField<T>(this IQueryable<T> q, string ColumnName)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, ColumnName);
var exp = Expression.Lambda(prop, param);
string method = "Select";
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}
我收到以下错误
无法转换类型为'System.Data.Entity.Infrastructure.DbQuery 1[System.String]' to type 'System.Linq.IQueryable
1'的对象。
我参考以下方法尝试了上述方法
public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, SortField);
var exp = Expression.Lambda(prop, param);
string method = Ascending ? "OrderBy" : "OrderByDescending";
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}
答案 0 :(得分:1)