I have the following problem:
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; }
The problem is now, that I can't check the User object for null. Before I get there, I get an InvalidOperationException
saying "The sequence contains no elements".
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?!)
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.
When you get the LINQ error "Sequence contains no elements", this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault() . This can also be caused by the following commands: FirstAsync()
SingleOrDefault<TSource>(IEnumerable<TSource>) Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.
Default value for the element is default(type). For classes default value is 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);
Try changing .First()
to .FirstOrDefault()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With