簡體   English   中英

ASP.Net MVC Linq to Sql如何處理null datetime

[英]ASP.Net MVC Linq to Sql how to handle a null datetime

我有一個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();

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

無論如何改變這條線:

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

...如果DateOfPost為null,它不會出錯?

您可以使您的財產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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM