mac8008
mac8008

Reputation: 31

Entity Framework return non null when no row should exist

I have the following query. I want the var to be null if the row does not exist but it always has a value. What am I doing wrong.

var results = dbContext.Users.Where(m => UserName == userName && Password == password).First();

if (results !=null)
     return true;

Upvotes: 1

Views: 3275

Answers (4)

Gopalakrishnan
Gopalakrishnan

Reputation: 517

Use FirstOrDefault() that will return null if the row does not exist.

  var results = dbContext.Users.Where(m => m.UserName == userName && m.Password == password)
                                        .FirstOrDefault();

    if (results !=null)
         return true;

Upvotes: 0

bobwah
bobwah

Reputation: 2568

I am surprised you are seeing a value if you expect the result of the Where to not return any results as First() would throw an exception on an empty collection. You could remove the Where method all together and put the predicate within the FirstOrDefault to make it cleaner like below:

var results = dbContext.Users.FirstOrDefault(m => UserName == userName && Password == password);

Upvotes: 2

Martin Vich
Martin Vich

Reputation: 1082

You should edit your code like this:

var results = dbContext.Users.Where(m => m.UserName == userName && m.Password == password).FirstOrDefault();

Explanation Since the diff might not be visible at the glance look, the problem with the query is that "m" is not used at all so as long as there is at least one user the results variable won't be null. That is also reason why the .First() is not throwing an exception when there is no match. This obviously expects that there are variables UserName and userName with same values (and same goes for password) but I don't think there is another possible explanation which would be buildable.

Upvotes: 1

Tim
Tim

Reputation: 15237

The FirstOrDefault function is the one you're looking for. If there is one or more result, it will return that one. If there are no results, it will return the default value (which, in the case of your User object, is null)

var results = dbContext.Users.Where(m => UserName == userName && Password == password)
                             .FirstOrDefault();

Upvotes: 1

Related Questions