1

我的 sql server 2008 r2 数据库中有这一行,但我不明白:

2012-12-06 11:00:36.703 and is of type DATETIME

当我在视图中显示它时,它是:

Mon, Jan 1, 0001 

这是我的代码:

var allNews = ZincService.NewsService.GetNewsPostsForId(id);

List<Zinc.Web.Areas.News.ViewModels.Home.NewsPostsViewModel> newsItems = new List<NewsPostsViewModel>();

foreach (var newsItem in allNews)
{ 
  NewsPostsViewModel newsItemViewModel = new NewsPostsViewModel();
  newsItemViewModel.CommentDate = String.Format("{0:ddd, MMM d, yyyy}", newsItem.CommentDate);
}

public class NewsPostsViewModel
{
  public Entities.News.News MainNews { get; set; }
  public virtual string News { get; set; }
  public virtual int NewsId { get; set; }
  public virtual string CommentDate { get; set; }
}

  public List<DataModels.News.NewsPostsDataModel> GetNewsPostsForId(int id)
{
  using (SqlConnection conn = new SqlConnection(ZincModelContainer.CONNECTIONSTRING))
  {
    using (SqlCommand cmd = conn.CreateCommand())
    {
      conn.Open();
      cmd.CommandType = System.Data.CommandType.StoredProcedure;
      cmd.CommandText = "[News].[GetNewsPostsForId]";

      SqlParameter param = new SqlParameter("@Id", System.Data.SqlDbType.Int);
      param.Value = id;
      cmd.Parameters.Add(param);

      List<DataModels.News.NewsPostsDataModel> news = new List<DataModels.News.NewsPostsDataModel>();

      using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
      {
        DataTable dt = new DataTable();
        adapter.Fill(dt);

        foreach (DataRow row in dt.Rows)
        {
          string message = Convert.ToString(row["NewsDescription"]);
          news.Add(new DataModels.News.NewsPostsDataModel { NewsPostId = id ,Message = message});
        }
      }

      return news;
    }
  }
}

public class NewsPostsDataModel
{
  public virtual int NewsPostId { get; set; }
  public virtual string Message { get; set; }
  public virtual DateTime CommentDate { get; set; }
}

有人能帮助我吗?

4

1 回答 1

3

这就是问题:

news.Add(new DataModels.News.NewsPostsDataModel { NewsPostId = id ,Message = message});

你没有CommentDate在这里填充,所以它的默认值是DateTime.MinValue.

当然,我们现在根本无法判断您的存储过程是否返回该值,但假设它返回,您大概应该从 中获取它DataRow并将其放入您的模型中......

在您修复代码之前,您应该退后一步并考虑您的诊断过程。您是否尝试对此进行调试?添加日志记录?您应该能够很快看到CommentDate模型中没有 a,然后尝试找出为什么没有 a CommentDate,这应该会引导您回到创建模型实例的代码。如果您可以改进您的诊断过程,您就可以大大加快您未来的发展,而不必问那么多问题。

于 2012-12-06T11:17:42.847 回答