LINQ to SQL 检查日期时间为空或小于当前日期



我需要进行将运行SQL查询的LINQ查询

Select * from Employee where Employee.StartDate is null OR 
(Employee.StartDate is not null AND Employee.StartDate > GetDate())

我尝试了以下代码

Employee.Where(e => e.StartDate == null || 
(e.StartDate != null && e.StartDate > Datetime.Today);
Employee.Where(e => e.StartDate.HasValue == false || 
(e.StartDate.HasValue != false && e.StartDate > Datetime.Today);
Employee.Where(e => e.StartDate..Equals((DateTime?)null) || 
(e.StartDate.HasValue != false && e.StartDate > Datetime.Today);

但它没有生成正确的 SQL 来检查两者。

我似乎无法在评论中说出我的意思。几乎可以肯定属性StartDate已根据需要映射。这可以通过数据注释来完成...

[Required]
public DateTime? StartDate { get; set; }

。或通过流畅的映射,例如在OnModelCreating...

modelBuilder.Entity<Employee>()
.Property(e => e.StartDate).IsRequired();

只有在这些情况下,EF 才会忽略 LINQ 表达式中的(非(空检查,因为它知道该属性不能为 null。

当然,将可为 null 的属性标记为必需没有多大意义,因此您应该将其设置为不可空或不需要。

var thresholdDate = GetDate();
var employeesWithNewOrNoStartDate = dbContext.Employees
.Where(employee => employee.StartDate == null
|| employee.StartDate > thresholdDate);

用词来说:

从所有Employees的序列中,只取那些根本没有StartDateEmployees,或者具有相当新的StartDate

var NewGroupEmployees = dbContext.Employees
.Where(employee => employee.StartDate == null
|| employee.StartDate > DateTime.Today).ToList();

这应该返回一个包含所需结果的列表。

您可以尝试的另一个选项是在 SQL 中创建存储过程并从应用程序调用它。

最新更新