Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to validate if lambda query returns null

Tags:

c#

lambda

linq

I retrieve data from database with lambda like

 var obj = DBContext.MyTable.Where(x => x.ID == 2).SingleOrDefault().MyColumn;

Actually , in MyTable , there is no ID with 2 .
So I got this message .

Object reference not set to an instance of an object.

How can I validate it properly ?

like image 372
zey Avatar asked Dec 01 '22 21:12

zey


2 Answers

Just capture result of query into separate variable and check if any item found before accessing its properties:

var yourItem = DBContext.MyTable.Where(x => x.ID == 2).SingleOrDefault();
if (yourItem != null)
    obj = yourItem.MyColumn;

BTW you can pass predicate into SingleOrDefault method:

var yourItem = DBContext.MyTable.SingleOrDefault(x => x.ID == 2);

Also you can select your property before applying SingleOrDefault

var obj = DBContext.MyTable.Where(x => x.ID == 2)
                           .Select(x => x.MyColumn)
                           .SingleOrDefault();
like image 89
Sergey Berezovskiy Avatar answered Dec 09 '22 11:12

Sergey Berezovskiy


Another way to do this is using the "null-coalescing" ?? operator, which will use the second argument if the first argument is null.

var obj = (DBContext.MyTable.FirstOrDefault(x => x.ID == 2) ?? new MyTable()).MyColumn;

like image 30
Dannyh Avatar answered Dec 09 '22 12:12

Dannyh