[英]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.