Search code examples
asp.net-coreaspnetboilerplate

Why repository "Get" and "GetAsync" methods throw EntityNotFoundException instead of returning null if the entity doesn't exists?


Using the module-zero-core-template (fully updated), I recently had problems when a user asked for account deletion (it was the first time), a lot of places in my code were getting the "User" entity using Repository.Get(TPrimaryKey id) or Repository.GetAsync(TPrimaryKey id):

var user = _userRepository.Get(model.UserId);

Until now I didn't realize it was throwing an exception when the entity doesn't exists, but I had to replace all the calls by (or the equivalent async):

var user = _userRepository.FirstOrDefault(u => u.Id == model.UserId);

My code wasn't made to handle such exception, but only a null value in return.

My questions are:

  • Why an exception instead of a null value returned?
  • Is there a way to modify this behavior?

Thanx in advance.


Solution

  • This is because the implementation is doing it like that.

    If you want to find an entity without the exception being thrown, you have to use the FirstOrDefault(TPrimaryKey id) function.

    Edit(explanation):

    Is like saying Single(x => x.Id == 1). You are expecting a result, if it doesn't have that, it will throw an exception. That's why we have SingleOrDefault(expr) and SingleOrDefault(expr) or FirstOrDefault(expr) and First(expr). Same principal involved