UserAccount objUserAccount=null;
AutoMapper.Mapper.CreateMap<AccountBO, UserAccount>();
objUserAccount = AutoMapper.Mapper.Map<AccountBO, UserAccount>(lstAcc[0]);
Up to this point it is mapping AccountBO
properties fine.
Now I have to map object objAddressBO
properties to destination including above mapped values. for this I have written code as below following to above lines of code.
AutoMapper.Mapper.CreateMap<AddressBO,UserAccount>();
objUserAccount=AutoMapper.Mapper.Map<AddressBO,UserAccount>(objAddressBO);
But it's losing first time mapped values and returning only the last time mapped values.
Please let me know what changes I need to do to have both the values in my destination object.
You should only configure the mapping once. The best way to do this is by using profiles:
public class MyProfile : Profile
{
public override string ProfileName
{
get
{
return "MyProfile";
}
}
protected override void Configure()
{
AutoMapper.Mapper.CreateMap<AccountBO, UserAccount>();
AutoMapper.Mapper.CreateMap<AddressBO,UserAccount>();
}
}
This should then be initialised in an initialisation method (such as App_Start
for web projects)
You should also create a unit test to test the mapping has been configured correctly
[TestFixture]
public class MappingTests
{
[Test]
public void AutoMapper_Configuration_IsValid()
{
Mapper.Initialize(m => m.AddProfile<MyProfile>());
Mapper.AssertConfigurationIsValid();
}
}
If that all works fine, and assuming I have understood the question correctly, you want to initialise objUserAccount
from listAcc[0]
, then fill in some additional parameters from objAddressBO
. You can do this like:
objUserAccount = Mapper.Map<AccountBO, UserAccount>(lstAcc[0]);
objUserAccount= Mapper.Map(objAddressBO, objUserAccount);
The first map will create the object, and the second map will update the provided destination object.
Note that for this to work correctly you may need to fill out your mapping configuration a little to provide the correct behaviour. For example, if you wish to avoid updating a destination property you can use the UseDestinationValue
directive. If you want to apply a condition to the update you can use the Condition
directive. If you wish to ignore the property completely, you can use the Ignore
directive.
If required, more documentation can be found here.