简体   繁体   English

使用LINQ和Entity框架检查c#var中的空值

[英]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. 我对LINQ和Entity框架以及c#中的var关键字都很陌生,所以请原谅我,如果这听起来像一个'新手'的问题。

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. 即使数据库中不存在电子邮件,条目也不等于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. 因此,在执行下一批语句之前,我必须执行if (entry.Count() < 1)来检查现有条目,而不是if (entry == null) Is there any reason why the variable wouldn't be considered null? 是否有任何理由不将变量视为null?

In your example, entry will never be null . 在您的示例中, entry 永远不会null What you think of as null is in fact an IEnumerable<Entry> with no items. 您认为null的实际上是一个没有项目的IEnumerable<Entry>

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 在VB中

Dim entry = myDB.Entries.Where(Function(e) e.Email = entry.Email).SingleOrDefault() Dim entry = myDB.Entries.Where(Function(e)e.Email = entry.Email).SingleOrDefault()

If entry IsNot Nothing Then 如果输入IsNot Nothing Then

' we have a value '我们有价值

else 其他

' we dont have a value '我们没有价值

End If 万一

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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