AutoMapper, ProjectTo() – Instance Version
Full source code available here.
In my previous post I showed how to use the wonderful AutoMapper ProjectTo()
feature, the demo code shown worked with AutoMapper up to v8.1.1. It looked like this –
_salesContext.Products.OrderBy(p => p.ProductId).Take(count).ProjectTo<ProductModel>()
But this will not work with AutoMapper v9 and above. You will be promptly informed that No overload for the method ‘ProjectTo` takes 0 arguments.
What happened? Well, AutoMapper moved away from a static API to an instance only API.
To get this working you need to make a few minor changes compared to previous post.
In ConfigureServices(…)
replace this –
1Mapper.Initialize(cfg => {
2 cfg.AddProfile<MappingProfile>();
3});
With this –
services.AddAutoMapper(typeof(Startup));
Then in the controller, change this -
1public class ProductsController : ControllerBase
2{
3 private readonly SalesContext _salesContext;
4
5 public ProductsController (SalesContext salesContext)
6 {
7 _salesContext = salesContext;
8 }
9 // snip…
To this –
1private readonly SalesContext _salesContext;
2private readonly IMapper _mapper;
3
4public ProductsController (SalesContext salesContext, IMapper mapper)
5{
6 _salesContext = salesContext;
7 _mapper = mapper;
8}
9// snip..
And finally, the ProjectTo()
call changes from this –
1[HttpGet("projected/{count}")]
2public ActionResult GetProjected(int count)
3{
4 return Ok(_salesContext.Products.OrderBy(p => p.ProductId).Take(count).ProjectTo<ProductModel>());
5}
To this –
1[HttpGet("projected/{count}")]
2public ActionResult GetProjected(int count)
3{
4 return Ok(_mapper.ProjectTo<ProductModel>(_salesContext.Products.Take(count).OrderBy(p => p.ProductId).Take(count)));
5}
The SQL produced by the instance ProjectTo()
is the same as what was produced by the static version.
That’s it, easy once you figure it out.
Full source code available here.