【问题标题】:How do I define a SELECT TOP using LINQ with a dynamic query?如何使用带有动态查询的 LINQ 定义 SELECT TOP?
【发布时间】:2012-12-03 05:55:24
【问题描述】:

我想将动态 lambda 表达式传递给下面的函数,但我不确定如何在表达式对象上定义 .Take() 或 .OrderByDescending()。 如果我想调用下面的函数,那么我希望能够做到这一点:

dbprovider.Query = (x => x.ConfigurationReference == "172.16.59.175")
                   .Take(100)
                   .OrderByDescending(x.Date)
FindEntities(db, dbprovider.Query)

但我不能(这种语法无效)。有什么想法吗?

public static List<T> FindEntities<T>(TrackingDataContext dataContext, System.Linq.Expressions.Expression<Func<T, bool>> find) where T : class
{
    try
    {
        var val = dataContext.GetTable<T>().Where(find).ToList<T>();
        return val;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

【问题讨论】:

  • 您的异常处理程序没有任何用处,顺便说一句,并且确实做了一些坏事(它丢失了堆栈跟踪);您应该删除 try/catch - 这会使整个 FindEntities 方法看起来非常多余

标签: c# sql linq lambda


【解决方案1】:

参数类型:

System.Linq.Expressions.Expression<Func<T, bool>> find

这意味着它可以接受一个谓词(“where”子句),并且仅一个谓词。因此,您可以在其中传递的唯一位是过滤器:

x => x.ConfigurationReference == "172.16.59.175"

要做你想做的,你需要在FindEntities中添加其余的代码,这样它就变成了:

var val = dataContext.GetTable<T>().Where(find)
              .OrderByDescending(x => x.Date).Take(100).ToList<T>();

(另请注意,Take 确实应该在 OrderByDescending 之后)

您可以这样做的一种方法是:

public static List<T> FindEntities<T>(TrackingDataContext dataContext,
    System.Linq.Expressions.Expression<Func<T, bool>> find,
    Func<IQueryable<T>, IQueryable<T>> additonalProcessing = null
) where T : class
{
    var query = dataContext.GetTable<T>().Where(find);
    if(additonalProcessing != null) query = additonalProcessing(query);
    return query.ToList<T>();
}

然后调用:

var data = FindEntities(db, x => x.ConfigurationReference == "172.16.58.175",
    q => q.OrderByDescending(x => x.Date).Take(100));

但是,坦率地说,我不确定这样做有什么意义......调用者可以更方便地在本地完成所有这些操作,而根本不使用FindEntities。只是:

var data = db.GetTable<T>()
             .Where(x => x.ConfigurationReference == "172.16.58.175")
             .OrderByDescending(x => x.Date).Take(100).ToList(); 

甚至:

var data = db.SomeTable
             .Where(x => x.ConfigurationReference == "172.16.58.175")
             .OrderByDescending(x => x.Date).Take(100).ToList();

或者只是:

var data = (from row in db.SomeTable
            where row.ConfigurationReference == "172.16.58.175"
            orderby row.Date descending
            select row).Take(100).ToList();

【讨论】:

    猜你喜欢
    • 2011-01-03
    • 2012-08-16
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    相关资源
    最近更新 更多