[英]LINQ C# Null exception
任何人都可以解释为什么我有时会在这个插入方法上获得NULL异常? 正如所说的那样,有时候对我来说更令人困惑。
OrderLine表对datacontext(.dbml文件)中的表Product有所引用
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的产品时。 ProductFormatName的值不是NULL,并且它具有我预期的值:“PS3”。
另一件奇怪的事情是,为什么不抱怨:
ItemName = orderLine.Product.Name,
此coulmn也不允许空值。
这可能是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,
此coulmn也不允许空值。
我可以想到两个解释:
orderLine.Product.Name
不为null。 上面提到的错误可能只影响ProductFormatName
。 orderLine.Product.Name
为null,但是一个错误就足以立即终止语句。 只报告一个错误。 在修复第一个错误之前,不会报告其他错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.