Biểu thức Lambda (Chúng được sử dụng trong trường hợp, OrderBy, v.v.) không thể chứa bất kỳ mã C# cụ thể nào, chúng chỉ có thể chứa cây biểu thức, được dịch sang SQL. Bạn không thể gọi bất kỳ phương thức tùy ý nào ở đó, ngoại trừ các phương thức được đề cập trong tài liệu EF như SqlFunctions, v.v.
Để sắp xếp với tên trường tại thời gian chạy, bạn phải tạo biểu thức lambda trong thời gian chạy và chuyển nó trên.
public IEnumerable<TModel> Paginate(IQueryable<TModel> source, ref int totalPages, int pageIndex, int pageSize, string sortfield, SortDirection? sortdir)
{
totalPages = (int)Math.Ceiling(source.Count()/(double)pageSize);
if (sortdir == SortDirection.Descending)
{
return source.OrderByDescending(sortfield).Skip(pageIndex * pageSize).Take(pageSize).ToList();
}
else
{
return source.OrderBy(sortfield).Skip(pageIndex * pageSize).Take(pageSize).ToList();
}
}
public static class QueryableHelper
{
public static IQueryable<TModel> OrderBy<TModel>(this IQueryable<TModel> q, string name)
{
Type entityType = typeof(TModel);
PropertyInfo p = entityType.GetProperty(name);
MethodInfo m = typeof(QueryableHelper).GetMethod("OrderByProperty").MakeGenericMethod(entityType, p.PropertyType);
return(IQueryable<TModel>) m.Invoke(null, new object[] { q, p });
}
public static IQueryable<TModel> OrderByDescending<TModel>(this IQueryable<TModel> q, string name)
{
Type entityType = typeof(TModel);
PropertyInfo p = entityType.GetProperty(name);
MethodInfo m = typeof(QueryableHelper).GetMethod("OrderByPropertyDescending").MakeGenericMethod(entityType, p.PropertyType);
return (IQueryable<TModel>)m.Invoke(null, new object[] { q, p });
}
public static IQueryable<TModel> OrderByPropertyDescending<TModel, TRet>(IQueryable<TModel> q, PropertyInfo p)
{
ParameterExpression pe = Expression.Parameter(typeof(TModel));
Expression se = Expression.Convert(Expression.Property(pe, p), typeof(object));
return q.OrderByDescending(Expression.Lambda<Func<TModel, TRet>>(se, pe));
}
public static IQueryable<TModel> OrderByProperty<TModel, TRet>(IQueryable<TModel> q, PropertyInfo p)
{
ParameterExpression pe = Expression.Parameter(typeof(TModel));
Expression se = Expression.Convert(Expression.Property(pe, p), typeof(object));
return q.OrderBy(Expression.Lambda<Func<TModel, TRet>>(se, pe));
}
}
Giải pháp này chỉ hoạt động ở cấp độ đơn nhất, nhưng bạn có thể xem SDK sau đây thực hiện tất cả những việc đó.
Tuy nhiên, nếu bạn xem xét bản thân Entity REST SDK, nó có nhiều thứ và tất cả những thứ bạn có thể cần. Disclaimer: Tôi là Tác giả.
https://entityrestsdk.codeplex.com
Bạn đang gặp phải vấn đề gì? Dường như bạn nhận được một không phải tất cả các đường dẫn trả về một giá trị? – Sayse
Tôi nhận được "LINQ to Entities không nhận ra phương thức 'Phương thức tên phương thức', cụ thể hơn là phương thức" GetPropertyValue ". –