繁体   English   中英

使用AutoMapper映射子集合

[英]Mapping Child Collections using AutoMapper

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

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

考虑我有一个具有Location集合的Store

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的新实例。

创建地图时,您可以使用方法,该方法几乎可以执行任何操作。 例如:

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
}

使用此方法,您可以在StoreDTO传递一个Id ,它可以实例化位置:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM