C# AutoMapper - 使用相同的源和目标对象类型进行映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9980344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 11:29:01  来源:igfitidea点击:

AutoMapper - Map using the same source and destination object types

c#automapper

提问by Deano

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.

我正在使用 Automapper 获取两个相同类型的对象并映射任何已更改的新值。我尝试使用下面的代码,但它不断抛出错误,我什至不确定 Automapper 是否可以实现这一点。

For example:

例如:

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

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.

基本上,我需要将来自新对象“userDetailsNew”的任何新值复制到现有对象“userDetailsCurrent”——即使它们是相同的类型。这样我就可以用新值“更新”现有对象。我这样做的原因是因为我不确定将传入哪些用户详细信息 - 我需要在它们到达时映射它们。

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!

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

回答by Chris Farmer

This seems to work for me. My custom type:

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

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

My mapping code:

我的映射代码:

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?

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

回答by Cliff Mayson

This can be done using tuples and by creating a custom type converter deriving from Automapper's Abstract TypeConverter class.

这可以使用元组并通过创建派生自 Automapper 的 Abstract TypeConverter 类的自定义类型转换器来完成。

Say you had a source and destination class of:

假设您有一个源类和目标类:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public override string ToString()
    {
        return string.Format("Firstname: {0}, Lastname: {1}", FirstName, LastName);
    }
}

Then you could build the custom converter type as

然后您可以将自定义转换器类型构建为

public class CustomerPersonConverter : TypeConverter<Tuple<Person, Person>, Person>
{
    protected override Person ConvertCore(Tuple<Person, Person> source)
    {
        var orginalValues = source.Item1;
        var updatedValues = source.Item2;

        var result = new Person
            {
                FirstName = string.IsNullOrEmpty(updatedValues.FirstName) ? orginalValues.FirstName : updatedValues.FirstName,
                LastName = string.IsNullOrEmpty(updatedValues.LastName) ? orginalValues.LastName : updatedValues.LastName
            };

        return result;
    }
}

which could be used like

可以像这样使用

var orginal = new Person() {FirstName = "Clifford", LastName = "Mayson"};
        var updated = new Person() {FirstName = "Cliff"};

        Mapper.CreateMap<Tuple<Person, Person>, Person>().ConvertUsing<CustomerPersonConverter>();

        var result = Mapper.Map<Person>(new Tuple<Person, Person>(orginal, updated));

        Console.WriteLine(result);

Which would produce the result of keeping the original last name value as that was missing in the update but updating the firstname value eg.

这将产生保留原始姓氏值的结果,因为它在更新中丢失,但更新名字值,例如。

Firstname: Cliff, Lastname: Mayson

回答by Jared Beach

This is a known behavior of Automapper (see issue). You actually have to tell Automapper:

这是 Automapper 的已知行为(请参阅问题)。你实际上必须告诉 Automapper:

CreateMap<A,A>();
CreateMap<B,B>();
CreateMap<C,C>();
CreateMap<A,A>();
CreateMap<B,B>();
CreateMap<C,C>();