【问题标题】:Linq to SQL Left Join with where clause looking for condition or nullLinq to SQL Left Join with where 子句寻找条件或空
【发布时间】:2020-03-23 02:02:11
【问题描述】:

我需要从 2 个表中选择记录,并使用左连接。那部分很好。但是,在where子句中,我需要选择where t2.fromDate > 20190101 OR t2.fromDate is null

问题在于,在 c# 中,t2.fromDateint,而不是可为空的 int。我应该如何将t2.fromDate 与 null 进行比较?我试过t2.fromDate == 0,但这不起作用,因为在 SQL 中该值为 null,但在 C# 中则期望该值为 int。

int FromDate = 20190101;
var data = (from hi in DbContext.t1
        from fp in DbContext.t2.Where(x => x.DimHierarchyItemKey == hi.Key).DefaultIfEmpty()
        where fp.fromDate >= FromDate || ???

【问题讨论】:

  • 您不能将您的实体更新为int? 吗?
  • 很遗憾没有。我无法控制 db 架构,并且 C# pocos 是动态创建的,因此我所做的任何更改都必须每次都进行 post regen。
  • 如果t2.fromDateint,在C# 中它不可能是null,所以你可以总是假设它不为空。如果试图实例化一个空值,你会得到一个异常。

标签: c# linq-to-sql


【解决方案1】:

两种可能:

  1. 如果fp.OrderedDimDateKey 在数据库中可以为空,那么它在实体中也应该可以为空。

  2. (你的情况,我猜)如果fp.OrderedDimDateKey 在数据库中不可为空,那么在查询中为空的唯一方法是没有匹配的t2 实体。这意味着测试可以进行为

    where fp.OrderedDimDateKey >= FromDate || fp == null
    

【讨论】:

  • 谢谢你,@GertArnold!我下次试试。我的方式有效,但我从未想过你的方式。我稍后会测试它。谢谢你的建议。
【解决方案2】:

答案比我预期的要容易。

int FromDate = 20190101;
var data = (from hi in DbContext.t1
        from fp in DbContext.t2
                .Where(x => x.DimHierarchyItemKey == hi.Key).DefaultIfEmpty()
                .Where(x => x.fromDate>= FromDate).DefaultIfEmpty()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 2017-07-31
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多