gpt4 book ai didi

AutoMapper 和 "UseDestinationValue"

转载 作者:行者123 更新时间:2023-12-04 15:15:01 26 4
gpt4 key购买 nike

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);

并且输出是鲍勃?

最佳答案

我把整个问题都写了下来,然后想,呃!运行它看看。

它像我希望的那样工作。

这是我最终得到的代码:

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
Robert
Dan

关于AutoMapper 和 "UseDestinationValue",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7084346/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com