TWilly
TWilly

Reputation: 4933

Entity Framework Single Pretty Error Message

I have a lot of code that looks like this...

var employee = dbContext.Employees.Single(x => x.Id == dto.Id);

I use Single lookup to see if the record with gievn Id exists in the database before I edit it.

If the Id does not exist though I get an internal error and user doesn't know what happens.

How would I write clean code to catch this error and show a nice error message to user without using SingleOrDefault and checking null.

example (I could do this, but I would have to copy paste this code in 100+ locations)..

var employee = dbContext.Employees.SingleOrDefault(x => x.Id == dto.Id);
if(employee == null){
    throw new BusinessException("Could not find Employee");
}

Upvotes: 2

Views: 321

Answers (1)

Yuck
Yuck

Reputation: 50855

You can use this extension instead of SingleOrDefault():

public static T SingleOrDefaultWithErrorMessage<T>(this DbSet<T> entities, Func<T, Boolean> predicate = null, String entityName = "the record") where T : class
{
    var entity = predicate != null
                    ? entities.SingleOrDefault(predicate)
                    : entities.SingleOrDefault();
    if (entity != null)
        return entity;

    throw new ApplicationException($"Could not find {entityName}.");
}

I added an optional parameter so that you can specify what the friendly name should be for the entity.

Keep in mind that if predicate is not specific enough you can still get the exception Sequence contains more than one element which will probably be confusing for your users. You could also choose to handle that exception in this extension method.

Upvotes: 3

Related Questions