2013-08-28 43 views
-2

我有代碼:錯誤C#System.NullReferenceException

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」。我不知道什麼問題,請幫助我。

+0

在哪一行?只需在調試中運行它以查看哪個變量爲空... –

+0

哪些行是異常拋出? –

+0

當調試它不爲null有數據日期時間輸入。 –

回答

0

我想如果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(); 
+0

fromDate == toDate它意味着我在舉例「getOrderTotalModelByAgentID?agentIds = 687&fromdate = 2013-08-20&todate = 2013-08-20」 –

+0

如果沒有行,滿足條件,你的sQLQuery返回NULL。你不能從NULL中選擇。 – MikkaRin

+0

我解決了,謝謝你的幫助 –

相關問題