Maybe this is already solved somewhere but I can´t find a solution...
I work with EF Core and I want to get rid of lazyLoading. I want to write a generic method, which includes different NavigationProperties where needed. I have an Interface which defines crud-methods. I use AutoMapper to map the recieved entities to viewModels. I have different groups of entities. Some can be retrieved without any Navigations, others need specific navigationProperties included.
Actually I want to use one Base-Service-Interface and choose the right implementation during runtime. Or some conditional decision (as described below) in the Service-Implementation.
This is my Service:
public interface IService
{
Task<IEnumerable<TViewModel> GetAsync<TEntity, TViewModel>()
where TEntity : class
where TViewModel : class;
Task PostAsync<TEntity, TViewModel>(TViewModel model)
where TEntity : class
where TViewModel : class;
Task<TViewModel> PatchAsync<TEntity, TViewModel>(int id)
where TEntity : class;
}
This is my Navigation-Interface:
public interface INavigate
{
int NavigationTypeId {get;set;}
NavigationType NavigationType {get;set;}
}
This is my service-implementation:
public class Service
{
public async Task PatchAsync<TEntity, TViewModel>(Guid id,
JsonPatchDocument<TViewModel> patchDoc)
where TEntity : class
where TViewModel : class
{
var query = this.dbContext.Set<TEntity>();
if(typeof(INavigate).IsAssignableFrom(typeof(TEntity)))
{
query = this.dbContext.Set<TEntity>()
.Include(e=>e.NavigationType); // obviously this won't work
}
var entity = await query.FirstAsync();
var viewModel = this.mapper.Map<TViewModel>(entity);
patchDocument.ApplyTo(viewModel);
var updatedEntity = this.mapper.Map(viewModel, entity);
this.dbContext.Entry(entity).CurrentValues.SetValues(updatedEntity);
this.dbContext.SaveChangesAsync();
}
}
So... This isn't a solution. I think there must be some way to solve this problem somehow without generating different services for each Navigation-Interface and specific where-clauses (where TEntity : class, INavigate
) - but I don't know where to go from here.