Home > Blockchain >  LINQ not evaluating check for null object
LINQ not evaluating check for null object

Time:05-21

I'm wondering why my linq statement doesn't properly evaluate the null check on the Agency object which is a property of the Users model.

var invalidUsers = this.DbContext.Users.Where(p => p.Agency != null).ToList();    
var invalidUsersList = invalidUsers.Where(p => p.Agency != null).ToList();

When I run the code above, the first line returns a list of all Users, regardless of the Agency object being null or not. However, the second line executes and properly filters the list and returns a list that is correctly returning Users where Agency is not null.

CodePudding user response:

Chances are since this appears to be a foreign key table you need to include it first in LINQ so it can query against it.

So something like.

var invalidUsers = await this.DbContext.Users
.Include(p => p.Agency)
.Where(p => p.Agency != null)
.ToListAsync();  

Give that a try and see if it helps.

  • Related