I have a Topic parent table, and a Post table childed to the Topic table.
What I'm trying to do within the Linq query is return the last post date, from the linked Post table, however, if there are no Posts, then the query below fails, as DateTime is not nullable:
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.
The query is:
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();
My ViewModel is:
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; }
}
Is there anyway of changing this line:
LastPostDate = t.Posts.OrderByDescending(x => x.DateOfPost).FirstOrDefault().DateOfPost
...so that it doesn't error if DateOfPost is null?
DateTime?
– MarcinJuraszek Jun 20 '13 at 7:35