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 ?
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();
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With