Skip to content

Fix issue on UnitOfWork.Save #30

@Ian-Webster

Description

@Ian-Webster

This code from the UnitOfWork class assume that there were be a non zero result from the SaveChangesAsync method;

public async Task<bool> Save(CancellationToken token)
{
    try
    {
        return await _context.SaveChangesAsync(token) > 0;
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "UnitOfWork failed to save changes");
        return false;
    }
}

this is an invalid assumption - SaveChangesAsync only returns a positive number when there are rows inserted (i.e. an addition) for updates the value will be zero.

The code should be as follows instead;

public async Task<bool> Save(CancellationToken token)
{
    try
    {
        await _context.SaveChangesAsync(token);
        return true;
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "UnitOfWork failed to save changes");
        return false;
    }
}

To see a live example of this bug look at MovieRepository.SaveMovie in the Movies repo;

public async Task<bool> SaveMovie(Movie movie, CancellationToken token)
{
    var movieDao = movie.Id != Guid.Empty ? await _movieRepository.FirstOrDefault(m => m.Id == movie.Id, token): null;

    if (movieDao == null)
    {
        movieDao = new Repo.Movie
        {
            Id = movie.Id,
            Title = movie.Title,
            GenreId = (short)movie.Genre,
            YearOfRelease = movie.YearOfRelease,
            RunningTime = movie.RunningTime
        };
        if (!await _movieRepository.Add(movieDao, token)) return false;
    }
    else
    {
        movieDao.GenreId = (short)movie.Genre;
        movieDao.RunningTime = movie.RunningTime;
        movieDao.Title = movie.Title;
        movieDao.YearOfRelease = movie.YearOfRelease;
    }

    return await _unitOfWork.Save(token);
}

the final line returns false on edits.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions