1

enter image description hereHi,

I have the following ef query in my C# code.

        var user = await query
                    .Where(q => q.Email.Equals(email, StringComparison.OrdinalIgnoreCase))
                    .FirstOrDefaultAsync();

        if (user != null) // when i set a debug here i get attached error.
        {
            return user.Id;
        }

This error really confuses me. I am checking for null and it is throwing error at that line of code.

Mukil Deepthi
  • 6,072
  • 13
  • 71
  • 156
  • 2
    What is `user` here? Is it a type that overloads the `!=` operator for example? If you change to `if (user is object)` does that fix it? – Jon Skeet May 04 '22 at 10:15
  • 1
    Perhaps `q.Email` or variable `email` is null? Shouldn't throw an error there still but might contribute. What is `query` though? We are missing parts for a good answer. You might be forgetting an Include to the Users table, which I've seen throwing an exception once you try to access the property of a relational table. – CularBytes May 04 '22 at 10:23
  • Post the *full* exception text, not only the message. The stack trace and any inner exceptions would show where exactly the error was thrown. Perhaps `q.Email` was null? Perhaps the error occurred in the rest of the (missing) query? – Panagiotis Kanavos May 04 '22 at 10:32

1 Answers1

0

Have you declared the variable user?

To me this reads like you are trying to test:

Fetch object, is the value of object 'null'?

But may be actually testing:

Fetch object -... there is no object returned. A missing object does not have a value, this operation is undefined - throw error.

Make sure you have declared/instantiated your user variable before calling this function.

To test it, declare user = null;

If the variable is nullable, then your code should execute without error. If user is still not initialised, then the error will move to where you assign null to an undeclared variable.

_---

Oh it's async - make sure your async task has finished returning properly before you attempt to use the value.


I think this may be to do with your async operation or syntax.

Questions to think about:

  • What is the return type of the async query?
    • Is it nullable?
    • Is it variable?
  • Can you explicitly declare the variable before calling the async query, e.g. declare user as null, then call the query into the declared variable. See if the error still throws, or if it is just the query not returning.
  • Have you declared the async methods correctly, and are you blocking code in the correct place.

By declaring var user = something; its hard to really be sure what object user actually is. If your query is not returning a Task<> object, then your await may not be blocking.

Curt P
  • 29
  • 3