I want to pass a paramether to a mapping so then it decides a value based on that parameter.
A simple class
public class Person
{
string Name;
}
And its DTO
public class PersonDTO
{
string Name;
string IsAProgrammer;
}
I want something Like this
var parameterIsTrue = true; // how do I pass this value?
CreateMap<MyClassDTO, MyClass>()
.ForMember(x => x.Name, opt => opt.MapFrom(src => src.Name))
.ForMember(x => x.IsAProgrammer,
opt => opt.MapFrom(parameterIsTrue ? "sure!" : "nope"));
EDIT
I am Trying to write a Custom Resolver but can't figure how to pass arguments to it. I figured how to make the resolver:
public class PersonResolver : IValueResolver<Person, PersonDTO, string>
{
...
public string Resolve(Person src,
PersonDTO dest,
string destMember,
ResolutionContext context)
{
return (bool) context.Items["isProgrammer"] ? "sure!" : "nope";
}
}
But I'm still failing with the mapping:
CreateMap<MyClassDTO, MyClass>()
.ForMember(x => x.Name, opt => opt.MapFrom(src => src.Name))
.ForMember(x => x.IsAProgrammer,
opt => opt.ResolveUsing(PersonResolver)); // what ???
// how do I pass the context?
I found a solution to this problem that worked for my use case. I had details on an object I didn't want to load in some conditions.
I created this extension method for easy reuse for all the properties that met this criteria:
In your mapping profile, you can use the above extension method like so:
Then to set this condition when mapping, I created another helper extension method:
Which then you can call while mapping like so: