1

I have a database, where are tables User and UserDetail. Relation between tables is 1 : 0..1. User can have UserDetail.

I am using latest EF model database first.

Problem: when doing query over non existing reference (User dont have a UserDetail)

var details = User.UserDetail.FirstOrDefault(u => u.userID == 1)

then I am getting error

Object reference not set to an instance of an object

When User have UserDetail, so everthing is OK.

How to query over non existing reference to get a NULL to var details?

Pac0
  • 21,465
  • 8
  • 65
  • 74
Prochotor
  • 23
  • 3
  • If you're using C# 6 or above, null conditional operator may help assigning `null`: `var details = User.UserDetail?.FirstOrDefault(u => u.userID == 1)`. For C# 5 or below you need to check against null value for `User.UserDetails` first before using `FirstOrDefault`. – Tetsuya Yamamoto Apr 24 '18 at 08:41
  • ouu, thanks for fast question, it works! – Prochotor Apr 24 '18 at 08:46
  • 2
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – VDWWD Apr 24 '18 at 13:12

1 Answers1

0

Using this :

User.UserDetail?.FirstOrDefault(...)

will return null when User.UserDetail is null, without trying to dereference its value and call a function on it.

?. is called the null-conditional operator or sometimes null-safe navigation operator (or even Elvis operator), for your information.

If User can be null too, you can use several of these to handle this case :

User?.UserDetail?.FirstOrDefault(...)
Pac0
  • 21,465
  • 8
  • 65
  • 74