首页 > 解决方案 > 我想编写一个方法将订单更新到订单列表

问题描述

我收到了这个错误,我不知道我应该如何解决它:

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

标签: c#

解决方案


为什么要使用 SqlCommand?你为什么使用sp_前缀?为什么不使用 ORM?为什么要执行读取,而不是插入/更新,并忽略输入参数item以及无论如何newOrder调用的方法中的结果对象Upsert

您的构造函数参数为:OrderHeader order, int stockItemId, decimal price, string description, int quantity. 你需要按顺序传递所有这些东西。

你没有OrderHeader,你有OrderHeaderId。您可能需要在存储过程中添加对 OrderHeader 表的连接并将其返回,或者您需要重新考虑此方法的整个方法和整个代码库。


推荐阅读