使用 linq to Entity framework 按日期读取最近插入的行

Read most recently inserted rows by Date using linq to Entity framework

我的数据库中有一个日志 table,我只想根据列名 RowCreateDate 获取最近添加的那些记录,这就是我尝试获取带来的记录的方式来自数据库的行,但我觉得可能有更好的方法来实现相同的目标。

using (var context = new DbEntities())
        {
            // get date
            var latestDate = context.Logs.Max(o => o.RowCreateDate);

            if(latestDate!=null)
            {
                lastDate = new DateTime(latestDate.Value.Year, latestDate.Value.Month, latestDate.Value.Day,00,00,00);

                logs = context.Logs.Where( o.RowCreateDate >= lastDate).ToList();
            }
        }

我需要知道我做对了什么,或者还有其他更好的方法吗?

您无法简化此代码,因为 LINQ to Entities 不支持 TakeWhile 方法。

您可以使用

using (var context = new DbEntities())
{        
    // get date
    var latestDate = context.Logs.Max(o => o.RowCreateDate);

    if(latestDate!=null)
    {
        lastDate = new DateTime(latestDate.Value.Year, latestDate.Value.Month, latestDate.Value.Day,00,00,00);
        logs = context.Logs
            .OrderBy(o => o.RowCreateDate)
            .AsEnumerable()
            .TakeWhile(o => o.RowCreateDate >= lastDate);
    }
}

但是它从数据库中获取所有数据,这不是很好,我不推荐它。

我想这就可以了(如果我们假设你想获得前 3 名的最新记录):

var topDates = context.Logs.OrderByDescending(x=>x.RowCreateDate).Take(3)

首先,我认为你的代码很好。我没有看到这两个查询的问题。但是如果你想简化它,你可以使用 TruncateTime,像这样:

    IGrouping<DateTime?, Logs>  log =
        context.Logs.GroupBy(x => DbFunctions.TruncateTime(x.RowCreateDate))
            .OrderByDescending(x => x.Key).FirstOrDefault();

它将 return 一个分组结果,其中包含在 RowCreateDate 的最后一天创建的日志。

还有一个选择:

context.Logs.Where(c => DbFunctions.TruncateTime(c.RowCreateDate) == DbFunctions.TruncateTime(context.Logs.Max(o => o.RowCreateDate)))

这明显符合您的要求(获取日期等于最大日期的所有行)并且还会产生一个查询(而不是您可能预期的两个)。