【问题标题】:unable to get result showing Object reference not set to an instance of an object无法获得显示对象引用未设置为对象实例的结果
【发布时间】:2020-01-16 03:24:16
【问题描述】:

我想获取具有特定列值的表的最后一条记录。之后我需要增加值..这里表是空的,列属性是字符串

     public async Task<string> GetLastBillNo()
            {
                return this.DbSet.LastOrDefault().CustomOrderNumber;
            } // getting Object reference not set to an instance of an object”

bs逻辑是

 long billNo = 0;

     if (!string.IsNullOrEmpty(await invoiceRepository.GetLastBillNo()))
                    {
                        billNo = long.Parse(await invoiceRepository.GetLastBillNo());
                        billNo = billNo + 1;
                        order.CustomOrderNumber = billNo.ToString();
                    }
                    else
                        order.CustomOrderNumber = (billNo + 1).ToString();

【问题讨论】:

标签: c# linq asp.net-core asp.net-web-api


【解决方案1】:

在递增下一个值之前,您需要检查 null Object 引用。

        public async Task<string> GetLastBillNo()
        {
            return (this.DbSet.LastOrDefault() != null ? this.DbSet.LastOrDefault().CustomOrderNumber : string.Empty);
        }

【讨论】:

    【解决方案2】:

    订单类是静态的吗? 否则,您需要实例化订单对象。它不存在于上下文中。

    【讨论】:

    • 没有TropicalViking 它是一个实体..它包含已提交的“CustomOrderNumber”之一
    【解决方案3】:
    using (var order = new YourDBContext()) {
            if (!string.IsNullOrEmpty(await invoiceRepository.GetLastBillNo()))
                    {
                        billNo = long.Parse(await invoiceRepository.GetLastBillNo());
                        billNo = billNo + 1;
                        order.CustomOrderNumber = billNo.ToString();
                    }
                    else
                        order.CustomOrderNumber = (billNo + 1).ToString();
    ...rest of your code
        }
    

    【讨论】:

      猜你喜欢
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-08
      • 1970-01-01
      相关资源
      最近更新 更多