我想从带有 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);
}