c# - 我想编写一个方法将订单更新到订单列表
问题描述
我收到了这个错误,我不知道我应该如何解决它:
System.NullReferenceException:'对象引用未设置为对象的实例。''
此方法应该将新订单添加到订单列表中:
public int UpsertOrderItem(OrderItem item)
{
int result = 0;
sqlConn.Open();
sqlCommand = new SqlCommand("sp_UpsertOrderItem(@description, @price, @quantity)", sqlConn);
sqlCommand.Parameters.AddWithValue("@description", item.Description);
sqlCommand.Parameters.AddWithValue("@price", item.Price);
sqlCommand.Parameters.AddWithValue("@quantity", item.Quantity);
result = sqlCommand.ExecuteNonQuery();
sqlConn.Close();
return result;
}
这是我的 OrderItem 类:
public class OrderItem
{
public OrderItem(OrderHeader order, int stockItemId, decimal price, string description, int quantity)
{
OrderHeader = order;
StockItemId = stockItemId;
Price = price;
Quantity = quantity;
Description = description;
}
public string Description { get; set; }
public OrderHeader OrderHeader { get; set; }
public int OrderHeaderId { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public int StockItemId { get; set; }
public decimal Total
{
get
{
return Price * Quantity;
}
}
}
解决方案
为什么要使用 SqlCommand?你为什么使用sp_
前缀?为什么不使用 ORM?为什么要执行读取,而不是插入/更新,并忽略输入参数item
以及无论如何newOrder
调用的方法中的结果对象Upsert
?
您的构造函数参数为:OrderHeader order, int stockItemId, decimal price, string description, int quantity
. 你需要按顺序传递所有这些东西。
你没有OrderHeader
,你有OrderHeaderId
。您可能需要在存储过程中添加对 OrderHeader 表的连接并将其返回,或者您需要重新考虑此方法的整个方法和整个代码库。
推荐阅读
- node.js - NodeJS - 调用反序列化用户后,应用程序在身份验证期间挂起(passport.js)
- firefox - 跨不同端口的 CORS 请求在 Firefox 上未成功,但在 Chrome 上有效
- python - 如何使用'set'保持有序列表?
- android - 如何在 android 的启动画面中使用除应用程序图标之外的图像
- android - Android Studio 找不到我的虚拟设备
- scala - 在 Spark Scala 中找不到错误值
- ios - 以编程方式显示和隐藏视图控制器
- c++11 - 如何配置 xtensa-lx106-elf 使用 nonos-sdk 为 esp8266 编译 c++ 代码?
- automation - nornir 凝固汽油弹 jinja 模板问题
- protractor - 量角器 - Cucumber 配置查询