问题描述
我是很新的LINQ&安培;实体框架以及在C#中var关键字,所以请原谅我,如果这听起来像一个'新手'的问题。
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.
所以不是如果(入门== NULL)
我不得不这样做如果( entry.Count()。1)
检查现有条目之前,我执行我的下一批语句。没有任何理由,为什么变量将不被视为空?
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?
推荐答案
在你的榜样,进入
将的从不的是空
。你所认为的空
什么是实际上是一个的IEnumerable<输入方式>
有没有项目
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.
这篇关于检查与LINQ和放C#VAR空值;实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!