1

我正在使用 Automapper 制作对象的副本

我的域可以简化为以下示例

考虑我有Store一个集合Location

public class Store
{
    public string Name { get; set;}

    public Person Owner {get;set;}

    public IList<Location> Locations { get; set;}
}

下面是一个商店实例的例子

var source = new Store 
            {           
                Name = "Worst Buy",
                Owner = new Person { Name= "someone", OtherDetails= "someone" },
                Locations = new List<Location>
                            {
                                new Location { Id = 1, Address ="abc" },
                                new Location { Id = 2, Address ="abc" }
                            }
            };

我的映射配置为

var configuration = new ConfigurationStore(
                       new TypeMapFactory(), MapperRegistry.AllMappers());

configuration.CreateMap<Store,Store>();
configuration.CreateMap<Person,Person>();
configuration.CreateMap<Location,Location>();

我得到映射的实例

var destination = new MappingEngine(configuration).Map<Store,Store>(source);

我从映射中获得的目标对象有一个 Locations 集合,在源中存在相同的两个实例,即

Object.ReferenceEquals(source.Locations[0], destination.Locations[0])返回TRUE

我的问题是

如何配置 Automapper 在映射时创建新的 Location 实例。

4

1 回答 1

1

创建地图时,您可以使用一种方法,该方法几乎可以做任何事情。例如:

public void MapStuff()
{
    Mapper.CreateMap<StoreDTO, Store>()
        .ForMember(dest => dest.Location, opt => opt.MapFrom(source => DoMyCleverMagic(source)));
}

private ReturnType DoMyCleverMagic(Location source)
{
    //Now you can do what the hell you like. 
    //Make sure to return whatever type is set in the destination
}

使用此方法,您可以将它传递给它IdStoreDTO它可以实例化一个位置:)

于 2014-02-21T18:43:31.793 回答