2014-03-05 105 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中。 –