如何在Linq Select语句中将函数作为Expression传递?

时间:2019-01-22 10:33:47

标签: c# linq-to-sql expression-trees

我有两种方法,它们从表中返回最小和最大日期:

private static DateTime? GetNewestDateFromStatistics(IDbConnection db)
{
        return db.Single<DateTime?>(db.From<Statistic>()
                                             .Select(e => Sql.Max(e.DateTimeCest));
}

private static DateTime? GetOldestDateFromStatistics(IDbConnection db)
{
        return db.Single<DateTime?>(db.From<Statistic>()
                                             .Select(e => Sql.Min(e.DateTimeCest));
}

我想要一种方法,并将Sql.Min或Sql.Max动态传递给Select,所以我的Method将具有其他参数。这是我尝试的方式:

Expression<Func<Statistic, DateTime>> expMin = i => Sql.Min(i.DateTimeCest);

private static DateTime? GetDateFromStatistics(IDbConnection db, 
                                                 Expression<Func<Statistic, DateTime>> exp)
{
   return db.Single<DateTime?>(db.From<Statistic>()
                                  .Select(e => exp.Compile().Invoke(e)));
}

会调用我的方法:

GetDateFromStatistics(db, expMin);

我遇到错误

  

“从范围”引用的“统计”类型的变量,但不是   定义的

任何帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:0)

只需尝试一下:

private static DateTime? GetDateFromStatistics(IDbConnection db, 
                                               Expression<Func<Statistic, DateTime>> exp)
{
   return db.Single<DateTime?>(db.From<Statistic>()
                                 .Select(exp));
}

答案 1 :(得分:0)

完全不确定为什么这里需要Expression,这似乎可以解决问题:

Func<Statistic, DateTime> expMin = i => Sql.Min(i.DateTimeCest);
...
private static DateTime? GetDateFromStatistics(IDbConnection db, 
                                                 Func<Statistic, DateTime> exp)
{
   return db.Single<DateTime?>(db.From<Statistic>().Select(exp));
}
...
GetDateFromStatistics(db, expMin);