简体   繁体   English

比较日期时间? Linq表达式内

[英]Comparing Datetime? inside Linq Expression

i am trying to return queries from a DB using Entity Framework and Linq on a Nullable DateTime field. 我正在尝试在可空的DateTime字段上使用Entity Framework和Linq从数据库返回查询。

I have the following code; 我有以下代码;

DateTime? from = new DateTime(year, month, 1);
DateTime? to = from.Value.AddMonths(1);

return context.Where<Job>(
          x => 
          x.NextDueDate?.Date >= from?.Date &&
          x.NextDueDate?.Date <= to?.Date).ToList();

Where Job is (reduced for brevity); 工作在哪里(为简洁起见);

public class Job : AuditableEntity
{
    ...
    public DateTime? NextDueDate { get; set; }

I tried this from the following stack link; 我从下面的堆栈链接中尝试过此方法;

Linq expression with nullable DateTime 具有可空DateTime的Linq表达式

However, when I try this I am getting the following error; 但是,当我尝试此操作时,出现以下错误;

An expression tree lambda may not contain a null propagating operator 表达式树lambda不得包含空传播运算符

Can anyone explain a solution to this please? 谁能解释一个解决方案?

As the exception message said you cannot use ? 如异常消息所述,您不能使用? .

// First day of a month. E.g. 2/1/2018 12:00:00 AM
DateTime from = new DateTime(year, month, 1);

// Last day of a month and end of that day. E.g. 2/28/2018 11:59:59 PM
DateTime to = from.AddMonths(1).AddTicks(-1); 

return context.Where<Job>(
    x =>
        x.NextDueDate != null &&
        x.NextDueDate >= from &&
        x.NextDueDate <= to).ToList();

You are setting public DateTime? 您要设置公共DateTime吗? NextDueDate { get; NextDueDate {get; set; 组; }. }。 So the default value won't be null. 因此默认值不会为null。

Please try below code, because the date time value won't be null in code even when you fetch the null date time column from db. 请尝试以下代码,因为即使您从db获取空日期时间列,日期时间值在代码中也不会为空。 Which have a default value equal to 1/1/0001 12:00:00 AM. 其默认值等于1/1/0001 12:00:00 AM。

DateTime from = new DateTime(year, month, 1);
DateTime to = from.Value.AddMonths(1);
DateTime dateTimeDefault = default(DateTime);

return context.Where<Job>(
          x =>  
          x.NextDueDate.Date != dateTimeDefault
          x.NextDueDate.Date >= from.Date &&
          x.NextDueDate.Date <= to.Date).ToList();

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

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