LP13
LP13

Reputation: 34079

How to access EF functionalities in Clean architecture and .NET core

The EF core includes functionalities that you may want to use for complex queries. For example AsNoTracking(), SumAsync, MaxAsync or finding changed/modified entities etc. are available in Microsoft.EntityFrameworkCore assembly

In clean architecture the ApplicationCore layer does not allow direct access to DBContext, and data can be accessed only via common repository interface and specifications

I understand the idea of separation of concern and abstracting persistent layer from domain layer. And in future if you change the DB you only need to change persistent layer. However in reality, in enterprise level application how often you change the database. Once its in production it becomes harder to simply replace it.

public class ToDoItemSearchService : IToDoItemSearchService
{
  private readonly IRepository<Project> _repository;

  public ToDoItemSearchService(IRepository<Project> repository)
  {
    _repository = repository;
  }

  public async Task<Result<List<ToDoItem>>> GetAllIncompleteItemsAsync(int projectId, string searchString)
  {
     var project = await _repository.GetBySpecAsync(projectSpec);   
    // how to load entities without tracking
  }
}

How to access EF functionalities? Should the repository expose those? For example

public interface IRepository<TEntity>
{
      List<TEntity> GetBySpecAsync>(...);
      List<TEntity> GetBySpecAsyncWithNoTracking(...)

}

Upvotes: 1

Views: 532

Answers (1)

JanH
JanH

Reputation: 117

You can break any paradigm you want if you think that the benefits may out weights the cons of breaking the pattern/paradigm.

If you design repository class I would recommend to not even think how to make it the most generic repository and try to not to expose the the implementation details.

Does your application logic even care about tracking / no tracking things? In 90% i would say it does not -> create specific method in interface for each use case (e.g. yours GetBySpec(), if special use case needs other special result (max, no tracking, order by) simply create another method called e.g. GetBySpecByName(),. The number of use cases your repository will need to cover will be less than 5% of all features that EF provides, so it is not even worth to create advanced solutions how to expose everything )

Upvotes: -2

Related Questions