我可以使用自动映射器将多个对象映射到目标对象吗

2024-01-25

UserAccount objUserAccount=null;
AutoMapper.Mapper.CreateMap<AccountBO, UserAccount>();
objUserAccount = AutoMapper.Mapper.Map<AccountBO, UserAccount>(lstAcc[0]);

到目前为止,它正在映射AccountBO属性很好。

现在我必须映射对象objAddressBO到目的地的属性,包括上面的映射值。为此,我在上面的代码行之后编写了如下代码。

AutoMapper.Mapper.CreateMap<AddressBO,UserAccount>();
objUserAccount=AutoMapper.Mapper.Map<AddressBO,UserAccount>(objAddressBO);

但它会丢失第一次映射值并仅返回最后一次映射值。

请让我知道我需要进行哪些更改才能在目标对象中拥有这两个值。


您应该只配置一次映射。最好的方法是使用配置文件:

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>();
    }
}

然后应该在初始化方法中对其进行初始化(例如App_Start对于网络项目)

您还应该创建一个单元测试来测试映射是否已正确配置

[TestFixture]
public class MappingTests
{
    [Test]
    public void AutoMapper_Configuration_IsValid()
    {
        Mapper.Initialize(m => m.AddProfile<MyProfile>());
        Mapper.AssertConfigurationIsValid();
    }
}

如果一切正常,并且假设我正确理解了问题,那么您想要初始化objUserAccount from listAcc[0],然后填写一些附加参数objAddressBO。你可以这样做:

objUserAccount = Mapper.Map<AccountBO, UserAccount>(lstAcc[0]);
objUserAccount= Mapper.Map(objAddressBO, objUserAccount);

第一个映射将创建对象,第二个映射将更新提供的目标对象。

请注意,为了使其正常工作,您可能需要稍微填写映射配置以提供正确的行为。例如,如果您希望避免更新目标属性,您可以使用UseDestinationValue指示。如果您想对更新应用条件,您可以使用Condition指示。如果您希望完全忽略该属性,可以使用Ignore指示。

如果需要,可以找到更多文档here https://github.com/AutoMapper/AutoMapper/wiki.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我可以使用自动映射器将多个对象映射到目标对象吗 的相关文章

随机推荐