AutoMapper-使用相同的源和目标对象类型进行映射 [英] AutoMapper - Map using the same source and destination object types

查看:350
本文介绍了AutoMapper-使用相同的源和目标对象类型进行映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Automapper来获取两个相同类型的对象,并映射所有已更改的新值.我尝试使用下面的代码,但是它总是抛出错误,我甚至不确定用Automapper是否可以实现.

I'm using Automapper to take two objects of the same type and map any new values that have changed. I tried using the code below, but it keeps throwing an error and I'm not even sure if this can even be achieved with Automapper.

例如:

        Mapper.CreateMap<UserDetails, UserDetails>();
        UserDetails userDetails = Mapper.Map<UserDetails, UserDetails>(userDetailsCurrent, userDetailsNew);

基本上,我需要复制从新对象"userDetailsNew"输入到现有对象"userDetailsCurrent"的所有新值-即使它们是同一类型.这样,我可以使用新值更新"现有对象.我这样做的原因是因为我不确定会传入哪些用户详细信息-我需要在用户到达时以及到达时对其进行映射.

Basically, I need to copy across any new values that come in from the new object "userDetailsNew" to the existing object "userDetailsCurrent" - even though they are of the same type. This way I can "update" the existing object with the new values. The reason I am doing this is because I am not sure what user details will be passed in - I need to map them as and when they arrive.

我通常使用Automapper来映射具有相似属性的不同对象-但我认为我可以利用Automapper的功能以这种方式实现相同的目的.甚至可能会有更好的解决方案-任何帮助将不胜感激!

I have normally used Automapper to map different objects with similar properties - but I thought that I could use the power of Automapper to achieve the same thing this way. There might even be a better solution - any help would be appreciated!

推荐答案

这似乎对我有用.我的自定义类型:

This seems to work for me. My custom type:

class MyType
{
    public int MyInt { get; set; }
    public string MyString { get; set; }
}

我的映射代码:

Mapper.CreateMap<MyType, MyType>();
var source = new MyType() {MyInt = 1, MyString = "Hello world"};
var dest = Mapper.Map<MyType, MyType>(source);

除了简单属性之外,您的自定义类型还有什么有趣的地方?

What is interesting about your custom type beyond simple properties?

这篇关于AutoMapper-使用相同的源和目标对象类型进行映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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