我使用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实例。
答案 0 :(得分: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
}
使用此方法,您可以在Id
中将其StoreDTO
传递给它,它可以实例化一个位置:)