我有一个SQL数据库建模这个类。
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 :(得分:1)
我假设Article
类看起来像这样:
Public Class Article
Public Property Dated as DateTime?
End Class
您应该使用EF从数据库获取DateTime?
,然后执行ToShortDateString
作为LINQ to Objects查询。 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())
}