我有一个主题父表和一个邮政表拼接到主题表。ASP.Net MVC Linq to Sql如何处理空的日期时间
我想在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为空?
使用可空类型:?''日期时间 – MarcinJuraszek