當我運行一個linq查詢時,只有當找到某個項目時才返回結果;如果找不到任何項目,則會拋出異常「未將對象引用設置爲對象的實例」c#linq異常:未將對象引用設置爲對象的實例
如何不拋出此異常?我只想返回一個結果,即使它是空的。
var id = db.table.Where(a => a.item == passed_item).FirstOrDefault().id;
當我運行一個linq查詢時,只有當找到某個項目時才返回結果;如果找不到任何項目,則會拋出異常「未將對象引用設置爲對象的實例」c#linq異常:未將對象引用設置爲對象的實例
如何不拋出此異常?我只想返回一個結果,即使它是空的。
var id = db.table.Where(a => a.item == passed_item).FirstOrDefault().id;
這種方法,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);
和下一步是一樣的。
var id = (from a in db.table
where a.item == passed_item
select a.id).FirstOrDefault();
這將確保它只在嘗試取消引用id
時發現某些內容。其他方面,id
將分配任何默認值爲id
屬性是(空或零)
好的答案!這隻能從數據庫中選擇ID字段 - 因此更高效 – 2014-11-21 17:31:17
可能重複[什麼是NullReferenceException,我該如何解決它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – paqogomez 2014-11-21 17:25:39