Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue on UnitOfWork.Save #30

Open
Ian-Webster opened this issue Mar 5, 2024 · 0 comments
Open

Fix issue on UnitOfWork.Save #30

Ian-Webster opened this issue Mar 5, 2024 · 0 comments

Comments

@Ian-Webster
Copy link
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant