blazor-starter-kit icon indicating copy to clipboard operation
blazor-starter-kit copied to clipboard

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

Open tohidazizi opened this issue 2 years ago • 0 comments

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:

  • https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.addasync?view=efcore-6.0

tohidazizi avatar Feb 03 '23 20:02 tohidazizi