use*_*710 1 c# mapping automapper
UserAccount objUserAccount=null;
AutoMapper.Mapper.CreateMap<AccountBO, UserAccount>();
objUserAccount = AutoMapper.Mapper.Map<AccountBO, UserAccount>(lstAcc[0]);
Run Code Online (Sandbox Code Playgroud)
到目前为止,映射AccountBO属性很好.
现在我必须将对象objAddressBO属性映射到目标,包括上面的映射值.为此,我在上面的代码行中编写了如下代码.
AutoMapper.Mapper.CreateMap<AddressBO,UserAccount>();
objUserAccount=AutoMapper.Mapper.Map<AddressBO,UserAccount>(objAddressBO);
Run Code Online (Sandbox Code Playgroud)
但它丢失了第一次映射值并仅返回最后一次映射值.
请让我知道在目标对象中同时包含两个值时需要做些哪些更改.
您应该只配置一次映射.最好的方法是使用配置文件:
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>();
}
}
Run Code Online (Sandbox Code Playgroud)
然后应该在初始化方法(例如App_StartWeb项目)中初始化
您还应该创建一个单元测试来测试映射是否已正确配置
[TestFixture]
public class MappingTests
{
[Test]
public void AutoMapper_Configuration_IsValid()
{
Mapper.Initialize(m => m.AddProfile<MyProfile>());
Mapper.AssertConfigurationIsValid();
}
}
Run Code Online (Sandbox Code Playgroud)
如果一切工作正常,并假设我理解正确的问题,你要初始化objUserAccount的listAcc[0],然后从一些额外的参数填写objAddressBO.你可以这样做:
objUserAccount = Mapper.Map<AccountBO, UserAccount>(lstAcc[0]);
objUserAccount= Mapper.Map(objAddressBO, objUserAccount);
Run Code Online (Sandbox Code Playgroud)
第一个地图将创建对象,第二个地图将更新提供的目标对象.
请注意,为了使其正常工作,您可能需要稍微填写映射配置以提供正确的行为.例如,如果您希望避免更新目标属性,则可以使用该UseDestinationValue指令.如果要将条件应用于更新,可以使用该Condition指令.如果您希望完全忽略该属性,可以使用该Ignore指令.
如果需要,可以在此处找到更多文档.