1

オブジェクトのコピーを作成するために 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);

マッピングから取得した宛先オブジェクトには、ソースに存在する同じ 2 つのインスタンスを持つ Locations コレクションがあります。

Object.ReferenceEquals(source.Locations[0], destination.Locations[0])戻り値TRUE

私の質問は

マッピング中に Location の新しいインスタンスを作成するように Automapper を構成するにはどうすればよいですか。

4

1 に答える 1

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
}

このメソッドを使用するIdStoreDTO、それを渡すことができ、場所をインスタンス化できます:)

于 2014-02-21T18:43:31.793 に答える