Checking for null value in c# var with LINQ & Entity framework
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 do if (entry.Count() < 1)
to check for existing Entry before 开发者_JAVA百科i execute my next batch of statements. Is there any reason why the variable wouldn't be considered null?
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.
"var" keywords make it possible to achieve any type based on the assignment at runtime, so when you query using "Where" the var entry becomes "IEnumerable" that is returned by Where, that's why you have to check for count.
In VB
Dim entry = myDB.Entries.Where(Function(e) e.Email = entry.Email).SingleOrDefault()
If entry IsNot Nothing Then
' we have a value
else
' we dont have a value
End If
精彩评论