我有一个Topic父表,和一个子表Post链接到Topic表上。我希望在Linq查询中返回最后一篇文章的日期,但是如果没有文章,下面的查询将失败,因为DateTime不可为空:'The cast to value type 'DateTime' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.' 查询如下:
var topic = db.Topics.Include(x => x.Posts).Include(x => x.Forum).Where(x => x.ForumId==id)
.Select(t => new TopicViewModel
{
TopicId =t.TopicId,
ForumId=t.ForumId,
Title=t.Title,
DateOfTopic=t.DateOfPost,
Replies=t.Posts.Count()-1,
Author=t.Author,
Views = t.Views,
LastPost = t.Posts.OrderByDescending(x => x.DateOfPost).FirstOrDefault().Author,
LastPostDate = t.Posts.OrderByDescending(x => x.DateOfPost).FirstOrDefault().DateOfPost
}).OrderByDescending(x=> x.DateOfTopic).ToList();
我的ViewModel是:
public class TopicViewModel
{
public int TopicId { get; set; }
[Required]
public string Title { get; set; }
public string Author { get; set; }
public DateTime DateOfTopic { get; set; }
public int Replies { get; set; }
public int Views { get; set; }
public string LastPost { get; set; }
public DateTime LastPostDate { get; set; }
public int ForumId { get; set; }
}
有没有办法更改这一行:
LastPostDate = t.Posts.OrderByDescending(x => x.DateOfPost).FirstOrDefault().DateOfPost
如何使代码在DateOfPost为空的情况下不出错?
DateTime?
- MarcinJuraszek