I am implementing clean architecture using the existing database, with scaffolding command I have generated the POCO entities in the Infrastructure layer and as well as manually created the entities in the domain layer to map them later.
in the Application layer, I have the generic interface repository with a few standard operations.
public interface IRepository<T> where T : class
{
Task<IReadOnlyList<T>> GetAllAsync();
Task<T> GetByIdAsync(int id);
Task<T> AddAsync(T entity);
Task UpdateAsync(T entity);
Task DeleteAsync(T entity);
}
As per the principles of Clean-Architecture, I am implementing it in the Infrastructure layer.
public class Repository<T> : IRepository<T> where T : class
{
protected readonly MyDBContext _MyDBContext;
public Repository( MyDBContext mydbContext)
{
_MyDBContext= mydbContext;
}
public async Task<T> AddAsync(T entity)
{
await _MyDBContext.Set<T>().AddAsync(entity);
await _MyDBContext.SaveChangesAsync();
return entity;
}
-----
----
I am using a Mediator pattern with CQRS, when I try to save the user from the API layer I will end up with the below exception.
System.InvalidOperationException: Cannot create a DbSet for 'ABC.Domain.Entities.User' because this type is not included in the model for the context. However, the model contains an entity type with the same name in a different namespace: 'ABC.Infrastructure.Models.User'.
It will be resolved if I can able to map the domain entity to the infrastructure entity in the above Repository implementation.
In the above implementation, the T is the ABC.Domain.Entities.User, not the ABC.Infrastructure.Models.User.
I can't pass the ABC.Infrastructure.Models.User from the Application layer ( because I can't add a reference to the Infrastructure layer in Application layer) due to the rule Clean Architecture all dependencies flow inwards and Core has no dependency on any other layer.
Please help me to map the incoming domain entity with the infrastructure entity in the above repository implementation so that I can use these general methods for other entity operations as well.
Check my skeleton repo.
In the above class, the "AddAsync" operation is in the generic repository (Repository.cs) and can be used for different insert operations with different domain entities in the future. And here I won't be knowing what is T :
public class Repository : IRepository where T : class
please advise me of the generic way to find and map the incoming domain entity with the data entity.