How to check if lambda request returns null

I am retrieving data from a lambda database like

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

In fact, MyTable no ID with 2.
Therefore, I received this message.

The reference to the object is not installed in the instance of the object.

How can I check it correctly?

+4
source share
5 answers

Just write the result of the query into a separate variable and check if any element is found before using it:

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

By the way, you can pass the predicate to the SingleOrDefault method:

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

You can also select your property before applying SingleOrDefault

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

Another way to do this is to use "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;

+3
source

You must first check if the return value is null, and then access it:

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

Not the most elegant way, but I don’t know another.

+2
source

I prefer DefaultIfEmpty () instead of .FirstOrDefault ()

and thus we can avoid if we check

eg

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

or

 var obj = DBContext.MyTable.Where(x => x.ID == 2).DefaultIfEmpty(string.Empty).MyColumn; 

The concept of DefaultIfEmpty is simple: it replaces an empty collection with a set of one default value.

The default value for int is 0. Thus, DefaultIfEmpty in the list gives a list with one null element.

Hope this helps.

+1
source
 var yourItem = DBContext.MyTable.Where(x => x.ID == 2).ToArray() if( yourItem.Length > 0) //do stuff 
0
source

Source: https://habr.com/ru/post/1484401/


All Articles