Mar*_*ark 3 c# linq asp.net-mvc linq-to-sql
我有一个Topic父表,一个Post表childed到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();
Run Code Online (Sandbox Code Playgroud)
我的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; }
}
Run Code Online (Sandbox Code Playgroud)
无论如何改变这条线:
LastPostDate = t.Posts.OrderByDescending(x => x.DateOfPost).FirstOrDefault().DateOfPost
Run Code Online (Sandbox Code Playgroud)
...如果DateOfPost为null,它不会出错?
你可以做你的财产 Nullable
public class x {
public DateTime? nullableDate {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
这应该可以解决您的问题.该问号确保您可以拥有Null该nullableDate物业
| 归档时间: |
|
| 查看次数: |
7196 次 |
| 最近记录: |