Checking for null value in c# var with LINQ & Entity framework
In your example, entry
will never be null
. What you think of as null
is in fact an IEnumerable<Entry>
with no items.
If you want to check if there is at least one entry with your criteria, you normally do something like:
var entries = myDB.Entries.Where(e => e.Email == entry.Email);
if (entries.Any()) {
// ...
}
If you know that there will be at most one entry, then you can also do:
var entry = myDB.Entries.Where(e => e.Email == entry.Email).SingleOrDefault();
if (entry != null) {
// ...
}
This is closer to what you imagined, but will throw an exception if there is more than one matching entry.
Related videos on Youtube
yulun
A web developer that knows abit of both front and back end development.
Updated on June 04, 2022Comments
-
yulun over 1 year
I'm quite new to LINQ & Entity framework as well as the var keyword in c# so please pardon me if this sounds like a 'newbie' question.
I have problems checking for null values after doing something like this:
var entry = myDB.Entries.Where(e => e.Email == entry.Email);
Even when the email does not exist in the database, entry does not equate to null.
So instead of
if (entry == null)
i had to doif (entry.Count() < 1)
to check for existing Entry before i execute my next batch of statements. Is there any reason why the variable wouldn't be considered null? -
yulun over 12 yearsthanks! great help and insight as i forgot that i was using DBContext to check for entries.
-
Jason Goemaat over 12 yearsYou could append .SingleOrDefault() to the query to get one result or null as well.
-
Bert Coerver almost 11 years
var
types are resolved at compile time, not at run time.dynamic
types are resolved at run time.