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

The implementation of IRepositoryAsync<T, TId>.AddAsync(T entity) is wrong #444

Open
tohidazizi opened this issue Feb 3, 2023 · 0 comments

Comments

@tohidazizi
Copy link

Summary:
The use of _dbContext.Set<T>().AddAsync(entity) is wrong based on EF Core documentation. Instead, use .Add(entity).

Explanation:
BlazorHero.CleanArchitecture.Application.Interfaces.Repositories.IRepositoryAsync<T, TId> has a method signature 'AddAsync(T entity)' which is implemented in BlazorHero.CleanArchitecture.Infrastructure.Repositories.RepositoryAsync<T, TId>.

The implementation is as:

    public async Task<T> AddAsync(T entity)
    {
        await _dbContext.Set<T>().AddAsync(entity);
        return entity;
    }

However, EF Core 6 documentation clearly states that .AddAsync() method should not be used by developers:

This method is async only to allow special value generators, such as the one
used by 'Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo',
to access the database asynchronously. For all other cases the non async method
should be used.

Fix:

  1. In IRepositoryAsync<T, TId>, Rename 'AddAsync(T entity)' to 'Add(T entity)'

  2. The implementation of IRepositoryAsync<T, TId>.Add(T entity), in the RepositoryAsync<T, TId>` class must be:

     public async Task<T> Add(T entity)
     {
         await _dbContext.Set<T>().Add(entity);
         return entity;
     }
    

Reference:

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