Reputation: 860
I have two classes
public class SourceClass
{
public Guid Id { get; set; }
public Guid Provider { get; set; }
}
public class DestinationClass
{
public Guid Id { get; set; }
public Guid Provider { get; set; }
public Guid CustomerId {get; set;}
}
I've initialized my mapping by using the following code
CreateMap<SourceClass, DestinationClass>();
And then in my controller, I have :
Mapper.Map<List<DestinationClass>>(requests)
where "requests" is a List of SourceClass objects being passed in to my controller.
Now, this code works and the mapping works as configured. However, I also get passed a CustomerId and want to set it in the DestinationClass accordingly.
Is there any way to do this while the mapping is occuring, so that I don't have to write an additional loop to set CustomerId in every object in the list?
Upvotes: 2
Views: 1837
Reputation: 20095
You can pass additional parameter by passing key-value
to mapper (as suggested by @LucianBargaoanu). The custom value resolver and map execution can be implemented as:
// Configuration
var configuration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SourceClass, DestinationClass>()
.ForMember(dest => dest.CustomerId, opt =>
opt.MapFrom((src, dest, destMember, context) =>
context.Items["CustomerId"]));
});
var mapper = configuration.CreateMapper();
//Sample source class
var sourceClass = new SourceClass { Id = Guid.NewGuid(), Provider = Guid.NewGuid() };
var destClass = mapper.Map<SourceClass, DestinationClass>(sourceClass,
opt => opt.Items["CustomerId"] = "96b4b6e6-7937-4579-ba01-4a051bc0b93b");
The CustomerId
member of destClass
object is populated with passed GUID.
Note:SourceClass
and DestinationClass
definition are taken from OP.
Upvotes: 4