I have a SQL Database modeling this classes.

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

I want to get a list of Languages and also the date of the last article

But I have to check if the Articles have items, if the article have a valid date.

What's the correct way to do the query? I've done this so far:

  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)
              }
有帮助吗?

解决方案

I assumed Article class looks like that:

Public Class Article
  Public Property Dated as DateTime?
End Class

You should get DateTime? from database using EF, and then perform ToShortDateString as LINQ to Objects query. EF won't be able to translate ToShortDateString to proper 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())
              }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top