ASP.Net MVC Linq到Sql如何处理空日期时间

本文关键字:处理 时间 日期 何处理 MVC Net Linq Sql ASP | 更新日期: 2023-09-27 18:19:04

我有一个Topic父表和一个Post子表。

我想在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();

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; }
}

有办法改变这一行吗?

LastPostDate = t.Posts.OrderByDescending(x => x.DateOfPost).FirstOrDefault().DateOfPost

…这样它就不会出错,如果DateOfPost是空的?

ASP.Net MVC Linq到Sql如何处理空日期时间

您可以将您的属性设置为Nullable

public class x {
public DateTime? nullableDate {get; set;}
}

这应该可以解决您的问题。问号确保在nullableDate属性中可以有Null

如果存在空值,则可以使用.GetValueOrDefault()指定默认值:

LastPostDate = t.Posts
    .OrderByDescending(x => x.DateOfPost)
    .AsEnumerable()
    .FirstOrDefault()
    .DateOfPost.GetValueOrDefault(DateTime.MinValue);

或者,您可以使LastPostDate在您的模型中为空:

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; }
}

我通常不在我的视图模型中使用可空类型,并在可能的情况下设置默认值。

e如果数据库中的DateOfPost列是空的,那么你的实体中的DateTime也应该是空的,就像你的viewmodel属性一样。或者,如果你不想让视图模型为null你可以输入null coalescer

t.Posts.OrderByDescending(x => x.DateOfPost).FirstOrDefault().DateOfPost ?? DefaultDate