自动映射器:映射到现有的嵌套复杂属性 [英] Automapper: Mapping onto existing nested complex property

查看:92
本文介绍了自动映射器:映射到现有的嵌套复杂属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于自动映射器:映射到现有的嵌套复杂属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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