簡體   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