Automapper:与ReverseMap()和ForMember双向映射()

编程入门 行业动态 更新时间:2024-10-15 00:26:25
本文介绍了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双向映射()

本文发布于:2023-11-16 06:54:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1601999.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:双向   Automapper   ReverseMap   ForMember

发布评论

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

>www.elefans.com

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