转换为值类型'DateTime'失败,因为实例化值为null [英] The cast to value type 'DateTime' failed because the materialized value is null

查看:408
本文介绍了转换为值类型'DateTime'失败,因为实例化值为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目抛出上述错误,因为表中的发货日期为空。我正在使用代码优先,并且在通用集和SQL表中,DateTime字段都声明为可为空。我正在用结果集填充gridview。理想情况下,当ShipDate字段为null时,我希望gridview显示为尚未发货,但是在这一点上,我很高兴能够显示记录。任何帮助是极大的赞赏。这是我正在使用的后台代码和上下文类:

My project is the throwing the above error because the Ship Date in my table is null. I am using Code First, and the DateTime field is declared as nullable both in the generic set and the SQL table. I am populating a gridview with the result set. Ideally, I would like to have the gridview display "not yet shipped" when the ShipDate field is null, but at this point, I would be happy just to be able to display the record. Any help is greatly appreciated. Here is the code-behind and the context class that I am using:

public class Order
    {
        [Key]
        public int OrderID { get; set; }
        public int CustomerID { get; set; }
        public string ShipAddress { get; set; }
        public string ShipCity { get; set; }
        public string ShipState { get; set; }
        public string ShipZip { get; set; }
        [ScaffoldColumn(false)]
        public string PaymentTransactionID { get; set; }
        [ScaffoldColumn(false)]
        public System.DateTime OrderDate { get; set; }
        public System.DateTime? ShipDate { get; set; }
        public virtual Customers Customers { get; set; }

        public List<OrderDetail> OrderDetails { get; set; }


    }

后面的代码是:

    public List<OrderDetail> FetchByOrderID()
    {
        int myOrderID = CusOrderId;
        ProductContext db = new ProductContext();


        return db.OrderDetails.Where(
            c => c.OrderID == myOrderID).ToList();
    }


推荐答案

我遇到了以上错误尝试通过LINQ获取最大值(date_column)时。该列被定义为NOT NULL,并且当查询中没有返回任何行时,它会尝试将null表示代表date列的DateTime属性。一种解决方案是将date列更改为NULLable,这将创建类型为DateTime?的实体属性?

I was getting the above error when trying to get the max(date_column) through LINQ. The column was defined as NOT NULL and when there are no rows returned in the query its trying to assign null to the DateTime property that's representing the date column. One solution is to change the date column to being NULLable which will create the entities property as type DateTime?

这篇关于转换为值类型'DateTime'失败,因为实例化值为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆