I'm trying to use Automapper projections on Entity Framework IQueryables.
On application start, I create and add all my mapping profiles which create maps with the non-static CreateMap method.
All those profiles are registered within my IoC container.
I get the missing mapping exception although I see the mapping profile in the instance of my mappingConfiguration.
What could be the problem? Am I missing something? I'm using Automapper 4.2.1
I've noticed that when adding a static Mapper.CreateMap, it works fine. Do projections work only with static API? I want to avoid the static API.
Full code:
public class ItemEntityToItemView : Profile
{
public override void Configure()
{
CreateMap<ItemEntity, ItemView>();
// Without this line, I get missing Map type configuration.
Mapper.CreateMap<ItemEntity, ItemView>();
}
}
public interface IEntitiesProjector
{
IQueryable<T> SelectTo<T>(IQueryable source);
}
public class EntitiesProjector : IEntitiesProjector
{
private readonly IMapperConfiguration _mapperConfig;
public EntitiesProject(IMapperConfiguration mapperConfig)
{
_mapperConfig = mapperConfig;
}
public IQueryable<T> SelectTo<T>(IQueryable source)
{
return source.ProjectTo<T>(_mapperConfig);
}
}
public class ItemsRepository : IITemsRepository
{
public IQueryable<ItemEntity> GetById(int id)
{
return _dbSet.Where(x => x.Id == id);
}
}
public class Service
{
private readonly IEntitiesProjector _projector;
public Service(IEntitiesProject entitiesProjector)
{
_projector = entitiesProjector;
}
public List<T> GetItem(int id)
{
IQueryable<ItemEntity> itemsQueryable = ItemsRepository.GetById(id);
return _projector.SelectTo<ItemView>(itemsQueryable);
}
}
My Autofac registration :
builder.RegisterAssemblyTypes().AssignableTo(typeof(Profile)).As<Profile>();
builder.Register(c => new MapperConfiguration(cfg =>
{
cfg.CreateMap<IdentityUser, AspNetUser>().ReverseMap();
})).AsSelf().As<IMapperConfiguration>().SingleInstance();
builder.Register(c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve)).As<IMapper>().InstancePerLifetimeScope();
builder.Register<EntitiesProjector>().As<IEntitiesProjector>().SingleInstance();