AutoMapper assigns wrong value with UseValue
I have the following piece of code:
Mapper.CreateMap<WorkOrderServiceTypeViewModel, WorkOrderServiceType>()
.ForMember(x => x.CompanyId, opt => opt.UseValue(_companyId));
Mapper.Map(model, workOrderServiceType);
When I run this, my clock shows _companyId is 16, but after starting Mapper.Map, workOrderServiceType.CompanyId is 11.
Am I doing something wrong here?
ETA: It looks like .UseValue is only executed once. Any ideas why?
For reference, here are my 2 models:
public class WorkOrderServiceTypeViewModel
{
public long Id { get; set; }
public string Name { get; set; }
public bool Residential { get; set; }
public bool Commercial { get; set; }
public bool Restoration { get; set; }
public bool Cleaning { get; set; }
public bool Storage { get; set; }
}
and the database model:
+3
source to share
2 answers
If you want to use runtime values for mapping, you need to use the runtime support in AutoMapper:
Mapper.CreateMap<WorkOrderServiceTypeViewModel, WorkOrderServiceType>()
.ForMember(x => x.CompanyId, opt => opt.ResolveUsing(res => res.Context.Options.Items["CompanyId"]));
Then in your cartographic code:
Mapper.Map(model, workOrderServiceType, opt => opt.Items["CompanyId"] = _companyId);
Your configuration must be static and run once - AutoMapper assumes this. Thus, in order to pass runtime values to the mapping, I provide a dictionary where you can use any value that will be used inside your mapping configuration.
+4
source to share