简体   繁体   中英

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 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”关键字使得可以在运行时基于赋值实现任何类型,因此当您使用“Where”查询时,var条目变为“IEnumerable”,由Where返回,这就是您必须检查计数的原因。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM