gpt4 book ai didi

linq - 时间:2019-01-01 标签:c#genericorderby

转载 作者:行者123 更新时间:2023-12-05 00:33:59 25 4
gpt4 key购买 nike

在我的基础存储库类中

我编写了这个函数,以便可以从数据库中检索已排序的数据集合。
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>() ;
}

我的目标是引入一个通用排序参数,以便我可以以这种方式调用该函数:
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

最佳答案

您正在使用 ObjectSet实现IQueryable<T> .这通过 System.Linq.Queryable 上的方法进行了扩展, 接受 Expression<Func<参数。使用那些 Expression 是正确的参数,因为您打算在数据库中执行,而不是在本地执行。

  • Func 是一个匿名委托(delegate),一种 .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

    关于linq - 时间:2019-01-01 标签:c#genericorderby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15064581/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com