[英]Mapping Child Collections using AutoMapper
I am using Automapper for making a copy of an object 我正在使用Automapper制作对象的副本
My domain can be reduced into this following example 我的域名可以简化为以下示例
Consider I have a Store
with a collection of Location
考虑我有一个具有
Location
集合的Store
public class Store
{
public string Name { get; set;}
public Person Owner {get;set;}
public IList<Location> Locations { get; set;}
}
Below is an example of a store instance 以下是商店实例的示例
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" }
}
};
My Mappings are configured as 我的映射配置为
var configuration = new ConfigurationStore(
new TypeMapFactory(), MapperRegistry.AllMappers());
configuration.CreateMap<Store,Store>();
configuration.CreateMap<Person,Person>();
configuration.CreateMap<Location,Location>();
I get the mapped instance as 我得到的映射实例
var destination = new MappingEngine(configuration).Map<Store,Store>(source);
The destination object I get from mapping has a Locations collection with the same two instances present in the source, that is 我从映射获得的目标对象具有一个Locations集合,其中包含源中存在的两个相同实例,即
Object.ReferenceEquals(source.Locations[0], destination.Locations[0])
returns TRUE
Object.ReferenceEquals(source.Locations[0], destination.Locations[0])
返回TRUE
My question is 我的问题是
How can I configure Automapper to create new instances of Location while mapping. 如何在映射时配置Automapper以创建Location的新实例。
When creating the maps you can use a method and that method can do pretty much anything. 创建地图时,您可以使用方法,该方法几乎可以执行任何操作。 For example:
例如:
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
}
Using this method you could pass it an Id
in the StoreDTO
and it can instantiate a location :) 使用此方法,您可以在
StoreDTO
传递一个Id
,它可以实例化位置:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.