繁体   English   中英

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

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

我的数据库中有一个日志表,只想获取基于列名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);
    }
}

但是它会从数据库中获取所有数据,这不是很好,我不建议这样做。

我认为这可以做到(如果我们假设您想获得前三名的最新记录):

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();

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

另一个选择:

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

这将显式读取您想要的内容(获取所有日期等于最大日期的行),并且还会导致一个查询(而不是您期望的两个查询)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM