2014-03-05 86 views
0

我有一個SQL數據庫建模這個類。LINQ中檢查可能的空值

Public Class Language 
    Public Property Name As String 
    Public Property Articles As List(Of Article) 
End Class 

Public Class Article 
    Public Property Dated as DateTime? 
End Class 

我想語言的列表,也是最後一篇文章

的日期,但我要檢查是否有物品的物品,如果物品有一個有效日期。

查詢的正確方法是什麼?我到目前爲止已經做到了這一點:

Dim query = From x In context.Languages 
       Order By x.Name 
       Select New MyViewModel() With { 
       .Name = x.Name, 
       .LastArticleDate = If(x.Articles.Count <> 0 AndAlso 
        x.Articles.OrderByDescending(Function(x) x.Dated).FirstOrDefault IsNot Nothing AndAlso 
        x.Articles.OrderByDescending(Function(x) x.Dated).FirstOrDefault.Dated.HasValue, 
        x.Articles.OrderByDescending(Function(x) x.Dated).FirstOrDefault.Dated.Value.ToShortDateString, 
        String.Empty) 
       } 
+0

爲什麼你在不可空的'DateTime'屬性上檢查'HasValue'屬性? 'Dated'確實是'DateTime?'? – MarcinJuraszek

+0

是的,DateTime可以爲空 – InfoStatus

回答

1

我認爲Article類看起來像:

Public Class Article 
    Public Property Dated as DateTime? 
End Class 

你應該使用EF從數據庫中獲得DateTime?,然後執行ToShortDateString作爲LINQ到對象查詢。 EF將無法將ToShortDateString轉換爲正確的SQL。

Dim query = From x In context.Languages 
      Order By x.Name 
      Select New With { 
       .Name = x.Name, 
       .LastArticleDate = x.Articles.OrderByDescending(Function(x) x.Dated).FirstOrDefault() 
      } 

Dim results = From x In query.AsEnumerable() 
       Select New MyViewModel() With { 
       .Name = x.Name, 
       .LastArticleDate = If(!x.LastArticleDate.HasValue, "", x.LastArticleDate.ToShortDateString()) 
       } 
+1

更好的是,將LastArticleDate作爲DateTime返回?並讓你的用戶界面處理格式化日期。這樣你就不需要結果查詢,並且可以直接投影到MyViewModel中。 –