The cast to value type 'DateTime' failed b

2019-06-28 00:50发布

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

3条回答
Animai°情兽
2楼-- · 2019-06-28 01:27

I was having a similar problem, same error.

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

查看更多
Luminary・发光体
3楼-- · 2019-06-28 01:35

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;}
查看更多
叛逆
4楼-- · 2019-06-28 01:39

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?

查看更多
登录 后发表回答