fullstackhero / blazor-starter-kit

Clean Architecture Template for Blazor WebAssembly Built with MudBlazor Components.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

tohidazizi opened this issue · comments

commented

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: