LINQ to SQL检查Datetime是否为null或小于当前日期

时间:2018-08-20 13:39:21

标签: c# entity-framework linq datetime

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

finish();
startActivity(getIntent());

我尝试了以下代码

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

,但是它没有生成正确的SQL来同时检查这两个方面。

3 个答案:

答案 0 :(得分:2)

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

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

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

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

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

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

答案 1 :(得分:1)

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

换句话说:

从所有Employees的序列中,仅取那些根本没有Employees或有一个相当新的StartDate的{​​{1}}

答案 2 :(得分:0)

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

这应该返回具有所需结果的列表。

您可以尝试的另一种选择是在SQL中创建一个存储过程,然后从您的应用程序中调用它。