2014-11-21 38 views
3

當我運行一個linq查詢時,只有當找到某個項目時才返回結果;如果找不到任何項目,則會拋出異常「未將對象引用設置爲對象的實例」c#linq異常:未將對象引用設置爲對象的實例

如何不拋出此異常?我只想返回一個結果,即使它是空的。

var id = db.table.Where(a => a.item == passed_item).FirstOrDefault().id; 
+1

可能重複[什麼是NullReferenceException,我該如何解決它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – paqogomez 2014-11-21 17:25:39

回答

12

這種方法,FirstOrDefault,將返回null,如果沒有被發現的對象。因此,如果您嘗試讀取id的值,則會拋出異常。爲了避免這種

的一種方法如下:

// I suppose that the id you want to read is an int. 
// If it isn't, please change the code correspondingly. 
int id; 
// Try to get the record. 
var record = db.table.Where(a => a.item == passed_item).FirstOrDefault(); 
// If you find the record you are looking for, then read it's id. 
if(record!=null) 
    id=record.id; 

更新

另一種選擇是將遵循DavidG在他的評論中建議:

var record = db.Table.FirstOrDefault(a => a.item == passed_item); 

和下一步是一樣的。

+4

或潛在的'db.Table.FirstOrDefault(a => a.item == passed_item)' – DavidG 2014-11-21 17:23:45

+1

@DavidG你是對的。我複製並粘貼了David的代碼,但我沒有注意到這一點。謝謝你的評論。 – Christos 2014-11-21 17:27:02

+0

不客氣!和哎呀,我忘了你的+1所以在這裏去... – DavidG 2014-11-21 17:31:45

1
var id = (from a in db.table 
     where a.item == passed_item 
     select a.id).FirstOrDefault(); 

這將確保它只在嘗試取消引用id時發現某些內容。其他方面,id將分配任何默認值爲id屬性是(空或零)

+0

好的答案!這隻能從數據庫中選擇ID字段 - 因此更高效 – 2014-11-21 17:31:17

相關問題