左外连接中的可空日期时间

时间:2015-11-08 21:47:09

标签: c# linq datetime linq-to-sql left-join

我正在尝试在3个表之间执行左外连接。但是,在创建输出时,会发生NullReferenceException。

我通过检查日期是否为空并将日期时间转换为可以为空的值来尝试以下几个选项。

如何在DateTime列上执行Left Outer Join?

var query = from t1 in A
    join t2 in B
    on t1.newAsset equals t2.newAsset into grp1
    join t3 in C
    on t1.newAsset equals t3.newAsset into grp2
    from t2 in grp1.DefaultIfEmpty()
    from t3 in grp2.DefaultIfEmpty()
    select new
    {
        asset = t1.newAsset,
        standbyIssuedBeforeTarget = t1.issueDate
        standbyReturnedBeforeTarget = (DateTime?)t2.issueDate // Tried casting to a nullable date
        //standbyReturnedDuringTarget = (t3.issueDate == null ? SqlDateTime.Null : t3.issueDate) // Tried comparing issueDate to null
    };

1 个答案:

答案 0 :(得分:0)

如果A中的t1行与B中的任何行都不匹配,则外部联接会创建一个t1t2为空的输出。 然后t2.issueDate会抛出NullReferenceException。 你可以在c#6之前写这样的东西:

standbyReturnedBeforeTarget = t2 == null ? (DateTime?)null : t2.issueDate

在C#6中:

standbyReturnedBeforeTarget = t2?.issueDate