【问题标题】:c# generic orderby时间:2019-01-01 标签:c#genericorderby
【发布时间】:2013-02-25 10:14:04
【问题描述】:

在我的基础存储库类中

我编写了这个函数,以便可以从数据库中检索已排序的数据集合。 T 是在类级别定义的泛型

public abstract class RepositoryBase<T> 
        where T : class

代码是这样的:

public IList<T> GetAll<TKey>(Expression<Func<T, bool>> whereCondition, Expression<Func<T, TKey>> sortCondition, bool sortDesc = false)
        {
            if (sortDesc)
                return this.ObjectSet.Where(whereCondition).OrderByDescending(sortCondition).ToList<T>();

            return this.ObjectSet.Where(whereCondition).OrderBy(sortCondition).ToList<T>() ;
        }

我的目标是引入一个 generic 排序参数,以便我可以这样调用函数:

repo.GetAll (model=>model.field>0, model=>model.sortableField, true)

我的意思是我可以通过匿名函数直接指定排序字段,因此使用 Intellisense...

很遗憾,这个函数不起作用,因为最后一行代码在编译时会产生错误。

我也试过打电话:

repo.GetAll<Model> (model=>model.field>0, model=>model.sortableField, true)

但这不起作用。

我应该如何编写函数来实现我的目标?

我正在使用 EF 5、c#、.NET 4.5

【问题讨论】:

  • 编译时错误是......? (任何时候您有错误,无论是编译时还是执行时,请在问题中包含它。不要让我们猜测。)
  • 我认为应该是 Func<...> 而不是 Expression>
  • 我完全被搞砸了。我的功能运行良好,但我用错误的 Where 条件调用它...我应该删除这个问题吗?无论如何@EliAlgranti,我从 .NET 教程中复制了 where 条件参数的模板。你能告诉我 Func<...> 和 Expression> 之间的区别以及为什么 Func<...> 应该更好地工作吗?
  • 另外,在这里我刚刚发现了一个类似的问题,在这里他们也使用 Expression> stackoverflow.com/questions/3828591/…

标签: linq entity-framework generics sql-order-by expression


【解决方案1】:

您正在使用实现IQueryable&lt;T&gt;ObjectSet。这是由System.Linq.Queryable 上的方法扩展的,它接受Expression&lt;Func&lt; 参数。使用那些Expression 参数是正确的,因为您打算在数据库中而不是本地执行。

  • Func 是一个匿名委托,一种 .net 方法。
  • Expression 是一棵树,可以编译成 Func,也可以翻译成 Sql 或其他东西。

您向我们展示了该方法的真正抽象用法,但不是该方法的实际使用,也不是编译器错误。我怀疑您可能犯的错误混淆了这两个类型参数。

你说:

repo.GetAll<Model> (model=>model.field>0, model=>model.sortableField, true)

但是这个方法的这个泛型参数代表了 sortableField 的类型。如果 sortableField 不是模型 - 这是错误的。

相反,您应该这样做:

Repository<Person> myRepo = new Repository<Person>();
myRepo.GetAll<DateTime>(p => p.Friends.Count() > 3, p => p.DateOfBirth, true);

如果指定排序类型会破坏您的预期使用模式,请考虑使用 IOrderer 隐藏该键:Store multi-type OrderBy expression as a property

【讨论】:

  • 非常感谢您的回复。在我上次的 cmets 中,我刚刚说过我在问题中编写的代码似乎运行良好。错误是由“where 条件”产生的。实际上 model.field>0 失败了,因为 field 是一个字符串...无论如何,我非常感谢您,因为您解决了我的另一个疑问...我会将您标记为已接受的答案,因为它很好地解释了表达式概念。
猜你喜欢
  • 2018-01-03
  • 1970-01-01
  • 2014-11-14
  • 2019-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多