LINQ C# Null exception
本文关键字:exception Null LINQ | 更新日期: 2023-09-27 18:32:27
谁能解释为什么我有时会在这个插入方法上出现 NULL 异常?如前所述,只是有时,这对我来说更加令人困惑。
表订单行具有对数据上下文中的表产品的引用(.dbml 文件)
public void insertNewOrder(string accountNumber, int orderId)
{
var order = orderRep.GetOrderById(orderId);
var orderlineData = orderLineRep.GetOrderLines(order.OrderID);
foreach (var orderLine in orderlineData)
{
int currentStatus = dlvRep.getAxOrderStatusNumber(orderLine.ItemNumber, 0);
string levering = "";
string status = dlvRep.getAxOrderStatus(orderLine.ItemNumber, currentStatus, out levering);
WebsiteOrderStatus insertNew = new WebsiteOrderStatus
{
AccountNumber = accountNumber,
OrderID = orderId,
ItemNumber = orderLine.ItemNumber,
ItemName = orderLine.Product.Name,
FormatName = orderLine.Product.ProductFormatName,
Quantity = orderLine.Quantity,
Price = orderLine.Price,
Status = status,
Levering = levering,
LastUpdatedStatus = currentStatus,
CreatedDate = DateTime.Now
};
db.WebsiteOrderStatus.InsertOnSubmit(insertNew);
db.SubmitChanges();
}
}
异常消息:
Cannot insert the value NULL into column 'FormatName', table 'GWportal.dbo.WebsiteOrderStatus'; column does not allow nulls. INSERT fails.
该语句已终止。
当我查找此代码无法找到产品格式名称的产品时。ProductFormatName 的值不是 NULL,它具有我预期的值,例如:"PS3"。
另一个奇怪的事情是,它为什么不抱怨:
ItemName = orderLine.Product.Name,
这也不允许空值。
这可能是orderLineRep.GetOrderLines(order.OrderID)
代码中的一个错误,导致orderLine.Product.ProductFormatName
设置为null
。
尝试添加一些调试代码:
foreach (var orderLine in orderlineData)
{
if (orderLine.Product.ProductFormatName == null) {
throw new Exception("ProductFormatName == null");
}
// ...
另一个奇怪的事情是,它为什么不抱怨:
ItemName = orderLine.Product.Name,
这也不允许空值。
我能想到两种解释:
-
orderLine.Product.Name
不为空。上面提到的错误可能只影响ProductFormatName
。 -
orderLine.Product.Name
为 null,但一个错误足以立即终止语句。只会报告一个错误。在修复第一个错误之前,不会报告还存在的其他错误。