我的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; }
}
有人可以帮助我吗?
答案 0 :(得分:3)
这是问题所在:
news.Add(new DataModels.News.NewsPostsDataModel { NewsPostId = id ,Message = message});
您没有在此处填充CommentDate
,因此它的默认值为DateTime.MinValue
。
当然我们现在无法判断你的存储过程是否完全返回值,但假设它存在,你应该从DataRow
获取并将其放入模型中......
在 修复代码之前,您应该退后一步,考虑一下您的诊断过程。你试过调试吗?添加日志?您应该能够非常快速地看到模型中没有CommentDate
,然后尝试找出为什么您没有CommentDate
,这应该让你回到创建模型实例的代码。如果您可以改进您的诊断过程,您可以通过不必提出尽可能多的问题来显着加快您未来的发展。