AutoMapper 和“UseDestinationValue”

2023-11-21

UseDestinationValue 有何作用?

我这样问是因为我有一个基类和继承类,对于基类,我希望 AutoMapper 为我获取现有值。

它会这样做吗? (我已经看过了,我能看到的唯一例子UseDestinationValue涉及列表。只适用于列表吗?

我可以这样做吗:

PersonContract personContract = new PersonContract {Name = 'Dan'};
Person person = new Person {Name = "Bob"};
Mapper.CreateMap<PersonContract, Person>()
      .ForMember(x=>x.Name, opt=>opt.UseDestinationValue());

person = Mapper.Map<PersonContract, Person>(personContract);

Console.WriteLine(person.Name);

输出是 bob 吗?


我写下了整个问题然后想,DUH!运行一下看看。

它如我所希望的那样工作。

这是我最终得到的代码:

class Program
{
    static void Main(string[] args)
    {
        PersonContract personContract = new PersonContract {NickName = "Dan"};
        Person person = new Person {Name = "Robert", NickName = "Bob"};
        Mapper.CreateMap<PersonContract, Person>()
            .ForMember(x => x.Name, opt =>
                                        {
                                            opt.UseDestinationValue();
                                            opt.Ignore();
                                        });

        Mapper.AssertConfigurationIsValid();

        var personOut = 
            Mapper.Map<PersonContract, Person>(personContract, person);

        Console.WriteLine(person.Name);
        Console.WriteLine(person.NickName);

        Console.WriteLine(personOut.Name);
        Console.WriteLine(personOut.NickName);
        Console.ReadLine();
    }
}

internal class Person
{
    public string Name { get; set; }
    public string NickName { get; set; }
}

internal class PersonContract
{
    public string NickName { get; set; }
}

输出是:

Robert
Dan
罗伯特
Dan

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AutoMapper 和“UseDestinationValue” 的相关文章