linq2SQL + OrderBy字符串值 [英] linq2SQL + OrderBy string value
问题描述
我想知道这是否可能
var table = _db.GetTable<T>();
var data = table.Where(t => !t.Deleted).OrderBy("Name");
我无法做t.Name,因为t仅具有ID和已删除
I cannot do t.Name as t only have Id and Deleted
包含此方法的基类如下
public class RepositoryBase<T> where T : class, Interfaces.IModel
IModel只知道Deleted和ID
IModel only knows of Deleted and Id
致谢
推荐答案
它的基础类型没有没有明显的Name
成员,因此我看不到它如何工作.
It the underlying type doesn't have an obvious Name
member, this I can't see how this would work.
如果问题是简单的,则您仅知道在运行时排序的列;然后要通过动态属性进行订购,您需要即时构建Expression
.这是我执行此操作的一些旧代码,应支持名称"和诸如"Customer.Name"(子属性)之类的内容;不过,我最近没有测试过:
If the problem is simpy that you only know the column to order by at runtime; then to order by a dynamic property you need to build an Expression
on the fly. Here's some old code I have that does this, and should support "Name" and things like "Customer.Name" (child properties); I haven't tested it recently, though:
public static class OrderExtensions {
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "OrderBy");
}
public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "OrderByDescending");
}
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "ThenBy");
}
public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "ThenByDescending");
}
static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName) {
ParameterExpression arg = Expression.Parameter(typeof(T), "x");
Expression expr = arg;
foreach(string prop in property.Split('.')) {
// use reflection (not ComponentModel) to mirror LINQ
expr = Expression.PropertyOrField(expr, prop);
}
Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), expr.Type);
LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);
return (IOrderedQueryable<T>) typeof(Queryable).GetMethods().Single(
method => method.Name == methodName
&& method.IsGenericMethodDefinition
&& method.GetGenericArguments( ).Length ==2
&& method.GetParameters().Length == 2)
.MakeGenericMethod(typeof(T), expr.Type)
.Invoke(null, new object[] {source, lambda});
}
}
这篇关于linq2SQL + OrderBy字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!