I'm using autommaper to map domain classes to model classes and viceversa. I need to encrypt/decrypt one property. When I map Model to Domain there isn't problem, work perefectly:
Mapper.CreateMap<EntityModel, Entity>().ForMember(dest => dest.Password, opt => opt.ResolveUsing(src => this.EncryptString(src.Password)))
But when map Entity to Model automapper crash and throws "Can't resolve this to Queryable Expression":
Mapper.CreateMap<Entity, EntityModel>().ForMember(dest => dest.Password, opt => opt.ResolveUsing(src => this.DecryptString(src.Password)))
I've tried with a Custom Value Resolver too, with same result:
Mapper.CreateMap<Entity, EntityModel>().ForMember(dest => dest.Password, op => op.ResolveUsing<PasswordResolver>().FromMember(x => x.Password));
public class PasswordResolver : ValueResolver<object, string>
{
protected override string ResolveCore(object source)
{
return "TEST";
}
}
As the documentation states, you can't use custom resolvers in queryable expressions:
https://github.com/AutoMapper/AutoMapper/wiki/Queryable-Extensions#supported-mapping-options
You can, however, use MapFrom:
Mapper.CreateMap<Entity, EntityModel>()
.ForMember(dest => dest.Password, op => op.MapFrom(src => "TEST"));
I'm guessing that's not actually what you want to do for that Password property but that's how you can fix the example.
I think what your issue is that you're trying to call .NET code in the query to the database which is erroring.
What you can do is wherever you use the projection instead of using .ProjectTo use .UseAsDataSource(Configuration).AfterProjection and .BeforeProjection. Both of these will allow you to get it to project the values into the right fields and then operate on the results to encrypt/decrypt so you get the actual values you're looking for.
Once you pass those 2, then you call .For();
Otherwise you're always operating on the actual SQL Query which can't execute .NET code obviously.