The cast to value type 'DateTime' failed because the materialized value is null

泪湿孤枕 提交于 2019-12-10 15:39:11

问题


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


    }

The code behind is:

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


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

回答1:


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?




回答2:


I use VB.Net, but had a similar problem. I do not know if you fixed your problem. But I declared the variable as Nullable(Of Date) and that did the trick to me. I am told that adding the "?" does the similar thing, but unfortunately did not work out for me, or I did not do it correctly. :o)

private DateTime? _settlementDate {get;set;}



回答3:


I was having a similar problem, same error.

Turns out I failed to setup my ConnectionString in the configuration.



来源:https://stackoverflow.com/questions/14177201/the-cast-to-value-type-datetime-failed-because-the-materialized-value-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!