是否可以在创建地图时告诉AutoMapper映射到嵌套属性的现有实例?
Is it possible to tell AutoMapper during map creating to map onto existing instance of nested property?
假设我有一堂课:
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;} }我想创建从SomeClass到SomeClass的映射,并使用它将属性映射到现有实例.
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);其中a和b是SomeClass的实例.问题在于此解决方案将属性映射到现有实例,但是创建了Complex的新实例,而不是将a.Complex映射到现有的b.Complex.
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.
是否可以配置AutoMapper以获得所需的行为?
Is it possible to configure AutoMapper to get desired behavior?
(这使我在使用Entity Framework时遇到许多问题).
(It's causing me a lot of problems with Entity Framework).
推荐答案我自己弄清楚了.解决方案非常简单.
I figured it out myself. Solution was pretty simple.
正确的地图创建如下:
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>();更多推荐
自动映射器:映射到现有的嵌套复杂属性
发布评论