我有一个 Topic 父表和一个 Post 表,它是 Topic 表的子表。
我在 Linq 查询中尝试做的是从链接的 Post 表中返回最后一个发布日期,但是,如果没有 Posts,那么下面的查询将失败,因为 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();
我的视图模型是:
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 为空就不会出错?