且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AutoMapper,如何在映射对象之间保留引用?

更新时间:2022-05-29 23:14:07

如果我理解这个问题,则您正在执行两个单独的映射操作-一个用于John,另一个用于Will.

If I'm understanding the question, you're performing two separate mapping operations - one for John, another for Will.

@Sunny是正确的. AutoMapper并非旨在执行此操作.您对Mapper.Map()进行的每个调用通常都独立于其他任何调用.通过使用HouseListConverter的相同实例,您可以获得在字典中缓存所有映射房屋的好处.但是您必须在全局范围内注册它,或者将其作为选项传递给要分组在一起的映射调用.这不仅是额外的工作,而且还在转换器内部深处隐藏了一个非常重要的实现细节.

@Sunny is right. AutoMapper is not designed to do this. Each call you make to Mapper.Map() is typically independent of any other. By using the same instance of the HouseListConverter, you get the benefit of caching all mapped houses in a dictionary. But you have to either register it globally or pass it as an option to the mapping calls you want grouped together. That's not just extra work, it's hiding a very important implementation detail deep within the converter.

如果您在一次操作中将John和Will都映射到一个集合中,则无需定制转换器或解析器即可得到所需的输出.

If you map both John and Will in one operation, by putting them into a collection, the output would be what you want without the need for a custom converter or resolver.

对于其他有类似问题的人来说,这可能是一个更容易的选择.

It may be an easier alternative for other people with a similar problem.

public void MapListOfPeopleWithSameHouse()
{
    Mapper.CreateMap<Person, PersonDTO>();
    Mapper.CreateMap<House, HouseDTO>();

    var people = new List<Person>();
    var house = new House() { Address = "123 Main" };
    people.Add(new Person() { Name = "John", Houses = new List<House>() { house } });
    people.Add(new Person() { Name = "Will", Houses = new List<House>() { house } });

    var peopleDTO = Mapper.Map<List<PersonDTO>>(people);
    Assert.IsNotNull(peopleDTO[0].Houses);
    Assert.AreSame(peopleDTO[0].Houses[0], peopleDTO[1].Houses[0]);
}