Skip to content

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

@tohidazizi

Description

@tohidazizi

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:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions