c# - 转换为值类型 'Int32' 失败

标签 c# asp.net-mvc linq lambda

我有以下代码。我收到错误:

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

最佳答案

听起来您的模型将其中一个属性定义为不可为空,但数据库将相应的列设置为可为空,并且其中有一个空值。当生成的阅读器尝试填充模型时,BOOM。不幸的是,我们无法告诉您是哪个属性,它甚至不需要是该代码中提到的属性之一,因为它可能是 FrobNumber。任何属性(property)Sales_inv_details代表。

您需要非常仔细地检查您的模型。从任何属性/列开始 Sales_inv_details代表。当您发现不匹配时:将其标记为可为空,然后重试。

关于c# - 转换为值类型 'Int32' 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38971103/

相关文章:

c# - 使用条形码字体打印

c# - 调试时编辑 C#

asp.net-mvc - 从 Ajax Post 操作加载 jqGrid

asp.net-mvc - 为什么在构建时, Razor 编译错误不会出现在VS2012中,并且可以解决吗?

c# - 如何过滤 xml 部分并将其保存为文件

c# - 使用 c# mvc4 阅读 rss 提要

c# - 正确的程序结构

c# - 使用 UDP 接收时安全地结束线程

javascript - 包含外部 javascript 的 ASP.NET MVC 4 问题

.net - LINQ to SQL 左外连接