【问题标题】:linq2SQL + OrderBy string valuelinq2SQL + OrderBy 字符串值
【发布时间】:2009-08-05 16:48:46
【问题描述】:

我想知道这是否可能

var table = _db.GetTable<T>();
var data = table.Where(t => !t.Deleted).OrderBy("Name");

我不能做 t.Name 因为 t 只有 Id 和 Deleted

包含此方法的基类如下所示

public class RepositoryBase<T> where T : class, Interfaces.IModel

IModel 只知道 Deleted 和 Id

问候

【问题讨论】:

  • 如果表有 Name 列来排序,为什么没有 t.Name?
  • 它是一个基类 public class RepositoryBase where T : class, Interfaces.IModel 该接口只包含 Deleted 和 Id,因为所有表都有这个

标签: c# linq-to-sql


【解决方案1】:

如果底层类型没有明显的Name 成员,我看不出这是如何工作的。

如果问题很简单,您只知道在运行时要排序的列;然后要通过动态属性订购,您需要即时构建Expression。这是我拥有的一些旧代码,它应该支持“名称”和“Customer.Name”(子属性)之类的东西;不过,我最近没有测试过:

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});
  }
}

【讨论】:

    【解决方案2】:

    我认为您需要为此实体创建一个特定的存储库,因为您的抽象模型不适合这种情况。比如:

    public class MyEntityRepository : RepositoryBase<MyEntity>
    

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 2019-12-21
      • 2016-03-08
      • 1970-01-01
      相关资源
      最近更新 更多