Sequence contains no elements error but I want to check for null

后端 未结 3 1385
旧时难觅i
旧时难觅i 2021-01-03 18:12

I have the following problem:

public Boolean Exists(String userName)
{
    IRepository = new UserRepository();
    User user = userRepository.Fir         


        
相关标签:
3条回答
  • 2021-01-03 18:58

    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);
    
    0 讨论(0)
  • 2021-01-03 18:58

    Use .FirstOrDefault() to prevent that error

    0 讨论(0)
  • 2021-01-03 19:14

    Try changing .First() to .FirstOrDefault().

    0 讨论(0)
提交回复
热议问题