问题描述
我有以下问题:
public Boolean Exists(String userName)
{
IRepository<User> = new UserRepository();
User user = userRepository.First(u => u.Name == userName);
if (user == null) return false;
// Exists!
return true;
}
问题是现在,我不能检查用户对象为null。在我那里,我得到一个出现InvalidOperationException
说:的序列不包含任何元素
这似乎很奇怪我,特别是我不想建立异常控制流(例如,在try..catch封装,并返回真/假的各个部分)。
This seems really weird to me, especially as I don't want to establish control flow with exceptions (e.g. encapsulate in try..catch and return true/false in the respective parts).
这是怎么回事?这是正常的或者是有什么毛病我的程序存储库(暗示?!)
What's going on here? Is this normal or is there something wrong with my respository (hint?!)
顺便说一句,这code ++工程的完全存在时,我正在寻找的元素(用户检索等)的。它只有在没有匹配不起作用。
By the way, this code works perfectly when the element that I'm looking for exists (the User is retrieved etc.). It only doesn't work when there is no match.
推荐答案
使用FirstOrDefault,而不是第一个。这将在一个空的集合的脸返回null。
Use FirstOrDefault instead of First. This will return null in the face of an empty collection.
IRepository<User> = new UserRepository();
User user = userRepository.FirstOrDefault(u => u.Name == userName);
这篇关于序列不包含任何元素错误,但我想检查null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!