簡體   English   中英

LINQ查詢僅在添加where子句后返回空引用

[英]LINQ query returns null reference only after adding where clause

我在一個方法中有2個鏈接的LINQ查詢。 第一個從具有“人XXXX-XXXX被標記為已刪除”格式的表行中獲取子字符串,然后提取XXXX-XXXX部分並將其放入包含XXXX-XXXX的對象中。

var ids = from m in _repo.GetMessages()
                       where m.tool == 7
                       select new IDs
                       {
                           ID = m.text.Substring(6, 11),
                           text = m.text
                       };

這將按預期返回數據。 然后,這些ID將加入到后續的“結果”查詢中:

var results = from gs in _repo.GetSample()
                          join c in _repo.Getcenters() on gs.Iid equals c.Iid_c
                          join id in ids on gs.id equals id.ID
                          select new Results
                          {
                              c_id = c.id,
                              iid_d = gs.Iid_d,
                              Id = gs.id,
                              Num = gs.num,
                              sts_dt = c.sts_dt,
                              store_dte = gs.Store_dte,
                              quantity = gs.Quantity
                          };

盡管我需要在結果查詢中添加where子句,但這種形式的查詢將返回預期的數據。 當我添加引用查詢中任何數據對象的where子句時,輸出將產生“對象引用未設置為對象的實例”。 沒有where子句,一切看起來很好。

我的第一個想法是第一個數據集中存在空項目,因此我添加了!= null子句,但沒有任何效果。 然后,我嘗試用一​​個Contains(ID)語句替換ID為ID的聯接,但這並沒有改變。 由於我之前已經編寫了許多鏈接的LINQ查詢,並以這種方式毫無問題地將它們鏈接起來,所以我的猜測是ID對象上的聯接可能會引起一些奇怪的事情。 有人對如何在其中添加where子句而不產生該錯誤有任何想法嗎? 謝謝!

解決了一段時間后,我決定嘗試將兩個查詢一起加入,這似乎可以解決問題。 為什么不確定我為什么不這樣做,但我猜對先前查詢的輸出的聯接觸發了空對象警告。 以下查詢可以正常工作:

var results = from gs in _repo.GetSample()
                      join c in _repo.Getcenters() on gs.Iid equals c.Iid_c
                      join ids in _repo.GetLogs() on gs.id equals ids.text.Substring(6,11)
                      where gs.quantity > 0
                      select new Results
                      {
                          c_id = c.id,
                          iid_d = gs.Iid_d,
                          Id = gs.id,
                          Num = gs.num,
                          sts_dt = c.sts_dt,
                          store_dte = gs.Store_dte,
                          quantity = gs.Quantity
                      };

這也是一個更好,更緊湊的查詢。 感謝大家!

from gs in _repo.GetSample().Where(s=>s.quantity>0) ...嘗試from gs in _repo.GetSample().Where(s=>s.quantity>0) ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM