比较可以为空的日期时间

时间:2014-02-17 08:53:23

标签: c# asp.net linq datetime nullable

我正在尝试比较我的linq查询中的日期,但我的c.DateRequired是一个可以为空的日期字段,我想只是比较没有时间的日期。如何在这种情况下转换c.DateRequired以获取日期。

   IEnumerable<SalesOrder> salesOrders = _uow.Repository<SalesOrder>().Query()
            .Filter(c => c.IsDeleted != true &&
                         (((c.DateRequired == DateTime.Today.Date)) && Period == 1) ||
                         (((c.DateRequired >= sDateP && c.DateRequired <= stDate)) &&
                          (Period == 2 || Period == 3)))
            .OrderBy(q => q.OrderBy(c => c.DateCreated))
            .Get()
            .Select(p => new
            {
                SalesOrder = p,
                SalesOrderDetailsList =
                    p.SalesOrderDetailsList.Where(pd => pd.IsDeleted != true),
                salesOrderDetailsComponentsList =
                    p.SalesOrderDetailsList.Select(c => c.SalesOrderDetailsComponentsList),
                SalesOrderDetailsComponentsInfoList =
                    p.SalesOrderDetailsList.Select(
                        i =>
                            i.SalesOrderDetailsComponentsList.Select(
                                info => info.SalesOrderDetailsComponentsInfoList))
            })
            .ToList()
            .Select(p => p.SalesOrder);

        return salesOrders;

    }

3 个答案:

答案 0 :(得分:1)

尝试使用以下内容:

.Where(x => x.DateRequired.HasValue && 
            EntityFunctions.TruncateTime(x.DateRequired.Value) == EntityFunctions.TruncateTime(DateTime.Today))
.ToList();

它非常适合我。

答案 1 :(得分:0)

您需要使用EntityFunctions.TruncateTime接受可空datetime来截断linq中的时间

EntityFunctions.TruncateTime(x.DateRequired) == EntityFunctions.TruncateTime(DateTime.Today)

答案 2 :(得分:0)

我回答similar question

如果您使用的是EntityFramework 6,则在linq查询中比较日期的推荐方法是DbFunctions.TruncateTime(m.PlanDate)和以前的版本EntityFunctions.TruncateTime(m.PlanDate)