使用AutoMapper映射子集合 [英] Mapping Child Collections using AutoMapper

查看:1447
本文介绍了使用AutoMapper映射子集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Automapper制作对象

I am using Automapper for making a copy of an object

我的域名是可以还原成下面的例子中

My domain can be reduced into this following example

考虑我有一个商店地点集合

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

Object.ReferenceEquals(source.Locations [0],destination.Locations [0])收益 TRUE

我的问题是

如何配置Automapper创建位置的新实例,同时映射。

How can I configure Automapper to create new instances of Location while mapping.

推荐答案

在创建的地图,你可以使用的方法和该方法几乎可以做到任何东西。例如:

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
}

使用这种方法,你可以通过它的编号 StoreDTO ,它可以实例化一个位置:)

Using this method you could pass it an Id in the StoreDTO and it can instantiate a location :)

这篇关于使用AutoMapper映射子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆