error c# System.NullReferenceException

本文关键字:NullReferenceException System error | 更新日期: 2023-09-27 18:29:22

我有代码:

 public OrderTotalModel getOrderTotalModelByAgentID(string AgentIDS = null, DateTime? fromDate = null, DateTime? toDate = null)
    {
        var session = SessionManager.CurrentSession;
        TruncateAmount truncateAmount = new TruncateAmount();
        string sql = @" SELECT sum(o.totalQuantity) TotalQuantity,sum(o.totalAmount) TotalAmount
                        FROM Orders o join workflows w on w.Step = o.Status 
                        inner join Agents a on a.ID = o.AgentID                            
                        where w.Step = o.Status   
                        and w.External = true and w.inactive = false
                        and o.AgentId in (:agentIDS) and o.approved = true";
        //Tu ngay
        if (fromDate.HasValue)
        {
            sql += " and Date(o.Created) >= Date(:fromDate)";
        }
        // Den ngay
        if (toDate.HasValue)
        {
            sql += " and Date(o.Created) <= Date(:toDate)";
        }
        var sqlQuery = session.CreateSQLQuery(sql)
              .AddScalar("TotalQuantity", NHibernateUtil.Double)
              .AddScalar("TotalAmount", NHibernateUtil.Double);
        sqlQuery.SetString("agentIDS", AgentIDS);
        if (fromDate.HasValue)
        {
            sqlQuery.SetDateTime("fromDate", (DateTime)fromDate);
        }
        if (toDate.HasValue)
        {
            sqlQuery.SetDateTime("toDate", (DateTime)toDate);
        }
        var result = sqlQuery.List<object[]>().Select(row => new OrderTotalModel()
        {
            TotalQuantity = (double)row[0],
            TotalAmount = truncateAmount.truncateAmt((double)row[1]),
        }).FirstOrDefault();
        return result;
    }

当我输入fromDate#toDate时,它返回true,但当我输入fromDate==toDate时出现错误"System.NullReferenceException"。我不知道是什么问题,请帮助我。

error c# System.NullReferenceException

我认为在fromDate == toDate的情况下,您的sql函数不会返回任何值。因此,您不能调用NULL.FirstOrDefault()

 var result = sqlQuery.List<object[]>().Select(row => new OrderTotalModel()
    {
        TotalQuantity = (double)row[0],
        TotalAmount = truncateAmount.truncateAmt((double)row[1]),
    }).FirstOrDefault();