Automapper: Mapping onto existing nested complex property

大兔子大兔子 提交于 2019-12-13 06:16:34

问题


Is it possible to tell AutoMapper during map creating to map onto existing instance of nested property?

Let's suppose I've got a class:

public class SomeClass
{
    public int Id {get; set;}
    public Complex Settings {get; set;}

}

public class Complex
{
    public int Id { get; set;}
    public string SomeText { get; set;}
}

I want to create map from SomeClass to SomeClass and use it to map properties onto existing instance.

Mapper.CreateMap<SomeClass, SomeClass>()
    .ForMember(src => src.Settings, opts => opts.MapFrom(src => Mapper.Map<Complex, Complex>(src));

Mapper.CreateMap<Complex, Complex>();

Mapper.Map<SomeClass, SomeClass>(a, b);

Where a and b are instances of SomeClass. The problem is this solution maps properties onto existing instance but creates new instance of Complex instead of mapping a.Complex onto existing b.Complex.

Is it possible to configure AutoMapper to get desired behavior?

(It's causing me a lot of problems with Entity Framework).


回答1:


I figured it out myself. Solution was pretty simple.

Correct map creation looks like this:

Mapper.CreateMap<SomeClass, SomeClass>()
.ForMember(src => src.Settings, opts => opts.Ignore())
.AfterMap((src, dst) => Mapper.Map<TestSettings,TestSettings>(src.TestSettings, dst.TestSettings); 

Mapper.CreateMap<Complex, Complex>();


来源:https://stackoverflow.com/questions/39150693/automapper-mapping-onto-existing-nested-complex-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!