Automapper ProjectTo does not allow mapping properties to custom methods

automapper automapper-6 entity-framework-6 linq

Question

I'm using EntityFramework 6.2.0 and Automapper 6.2.2. I need to map the entity Cart to CartDto. CartDto has a property Total which needs to be mapped to the result of Cart.GetTotal(). I'd like to use .ProjectTo to simplify the query, but if I do that I receive the error:

LINQ to Entities does not recognize the method GetTotal()

because the projection uses IQueriable and the method has no translation in SQL. Is there any way around this issue?

var automapperConfiguration = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Cart, CartDto>()
       .ForMember(x => x.Total, o => o.MapFrom(x => x.GetTotal()))
       .ForAllOtherMembers(x => x.Ignore());
});

var cartDto = dbContext.Carts
                       .ProjectTo<CartDto>(automapperConiguration)
                       .FirstOrDefault();
1
0
8/24/2018 2:13:15 PM

Popular Answer

This is not AutoMapper not allowing this, it's Entity Framework. AutoMapper merely takes your mapping configuration and builds a Select LINQ expression to the underlying query provider.

In your case, the underlying query provider is Entity Framework, which unsurprisingly won't understand any random method and how to translate that method into SQL. EF understands a few methods, like Count, Sum, some string/DateTime/primitive methods, but that's about it.

So the exception message is quite accurate - EF doesn't understand this method you've given it, and therefore has no way to translate that method to SQL.

There may be hope, however, if you check out the AutoMapper.EF6 package. It includes the DelegateDecompiler package that uses IL inspection to look at what your method does, de-compile it, and pass that result as an expression to the query provider.

If that seems complicated, it is, so you really better have an understanding of how LINQ works before proceeding.

0
8/24/2018 5:54:07 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow