Automapper:与ReverseMap()和ForMember双向映射() [英] Automapper: bidirectional mapping with ReverseMap() and ForMember()

查看:5931
本文介绍了Automapper:与ReverseMap()和ForMember双向映射()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我想要的实体映射到一个视图模型和后面的情况。我必须用ForMember()显式地指定映射,因为它们的属性不共享完全相同的名称。下面是我的课怎么看起来像一个简单的例子:

I have the case where I want to map an entity to a viewmodel and back. I have to specify the mapping explicitly with ForMember() because their properties do not share the exact same names. Here is a short example of how my classes look like:

public class PartTwo {
    public int Integer { get; set; }
}

public class PartTwoViewModel {
    public int PartInteger { get; set; }
}

和我想使用它们是这样的:

And I want to use them this way:

Mapper.CreateMap<PartTwo, PartTwoViewModel>()
    .ForMember(dst => dst.PartInteger, opt => opt.MapFrom(src => src.Integer))
    .ReverseMap();

var partTwoViewModel = new PartTwoViewModel() { PartInteger = 42 };
var partTwo = Mapper.Map<PartTwoViewModel, PartTwo>(partTwoViewModel);
Assert.AreEqual(partTwoViewModel.PartInteger, partTwo.Integer);

但它的属性PartInteger为整型不匹配。 (整数为0。)

But it does not match the property PartInteger to Integer. (Integer is 0.)

有没有一种方法,使这项工作? (当两个类的属性具有相同的名称它的作品。)我必须设置一些选项的方法ForMember()?

Is there a way to make this work? (When the properties of both classes have the same names it works.) Do I have to set some kind of option in the method ForMember()?

推荐答案

您可以这样定义你的配置:

You could define your configuration like this:

Mapper.CreateMap<PartTwo, PartTwoViewModel>()
    .ForMember(dst => dst.PartInteger, opt => opt.MapFrom(src => src.Integer));

Mapper.CreateMap<PartTwoViewModel, PartTwo>()
    .ForMember(dst => dst.Integer, opt => opt.MapFrom(src => src.PartInteger));

更新

下面是提交其中 ReverseMap 最初实现。从我可以在code看,它仅创建一个简单的反向映射。例如,在这种情况下,它会自动配置是等效的:

Here is the commit where ReverseMap was initially implemented. From what I can see in the code, it only creates a simple reverse mapping. For example, in this case it would automatically configure the equivalent of:

Mapper.CreateMap<PartTwoViewModel, PartTwo>();

要得到任何东西更复杂,我怕你将不得不手动进行配置。

To get anything more complex, I'm afraid that you're going to have to configure it manually.

这篇关于Automapper:与ReverseMap()和ForMember双向映射()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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