自动映射器:映射到现有的嵌套复杂属性

编程入门 行业动态 更新时间:2024-10-28 09:27:59
本文介绍了自动映射器:映射到现有的嵌套复杂属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以在创建地图时告诉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>();

更多推荐

自动映射器:映射到现有的嵌套复杂属性

本文发布于:2023-11-17 05:41:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609027.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   属性   映射器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!