user3775473 user3775473 - 3 months ago 32
C# Question

The cast to value type 'Int32' failed

I have the following code. I'm getting error:


The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.


var productItem = from sales
in db.Sales_inv_details
select new {
sales.Sales_Invoices.Customer.Cust_Id,
sales.Sales_Invoices.Customer.Customer_Name,
sales.Sales_Invoices.Employe.Emp_Name,
sales.Sales_Invoices.Employe.Emp_code,
sales.Sales_Invoices.Date_invoice,
sales.Item.Item_ID,
sales.Qty,
sales.Qty_Price,
sales.Item.Item_Name,
sales.Item.Item_Code,
Unit_Measure = sales.Item.TBL_Unit_Measure.Code,
sales.Sales_Invoices.Descrption,
sales.disc };

productItem = productItem
.Where(x => (x.Date_invoice >= model.Fromdate & x.Date_invoice <= (model.Todate)));

productItem = productItem
.Where(x => (x.Emp_code == model.Emp_code));

Answer

It sounds like your model defines one of the properties as non-nullable, but the database has the corresponding column as nullable, and has a null value in it. When the generated reader attempts to populate the model, BOOM. Unfortunately, we can't tell you which property, and it doesn't need to even be one of those mentioned in that code, since it could be the FrobNumber property of whatever Sales_inv_details represents.

You need to check your model very carefully. Start with the properties / columns on whatever Sales_inv_details represents. When you have found a mismatch: mark it as nullable, and retry.