【问题标题】:Limiting a query to the rows created today (Linq-to-Entities, Datetime)将查询限制为今天创建的行(Linq-to-Entities、Datetime)
【发布时间】:2014-05-05 18:36:56
【问题描述】:

所以我有这个查询:

var query = from r in context.Cars
            let h = context.CarHistories
                           .Where(u => r.ID == u.CarID)
                           .Where(u => u.EventID == intEventID)
                           .OrderByDescending(u => u.CreatedDate)
                           .FirstOrDefault()
            select new RefundListItem()
            {
                ID = r.ID,
                VendorID = r.VendorID,
                RecipientName = r.RecipientName,
                MostRecentSubmittedName = h.CreatedName,
                CreatedDate = h.CreatedDate,
            };

稍后,我将其添加到查询中,因为我只想要今天创建的行:

DateTime today = DateTime.Today;
query.Where(u => Convert.ToDateTime(u.CreatedDate) >= today);

由于某种原因,这个 where 语句根本不会影响查询。该查询仍会返回前几天创建的项目,而不是将它们限制为今天创建的行。

我也试过了,但也没用:

DateTime today = DateTime.Today.Date;
query.Where(u => Convert.ToDateTime(u.CreatedDate.Date) >= today.Date);

我正在使用 Linq-to-Entities(MVC 4、EF 4)。

【问题讨论】:

    标签: linq linq-to-entities


    【解决方案1】:

    Where 不修改query 实例,它返回一个添加了附加条件的新实例。将其分配回query 以使其工作:

    query = query.Where(u => Convert.ToDateTime(u.CreatedDate.Date) >= today.Date);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多