AutoMapper和"UseDestinationValue" [英] AutoMapper and "UseDestinationValue"
本文介绍了AutoMapper和"UseDestinationValue"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
UseDestinationValue做什么?
What does UseDestinationValue do?
我之所以问是因为我有一个基类和继承的类,对于基类,我希望让AutoMapper为我获取现有的值.
I am asking because I have a base and inherited class, and for the base class, I would love to have AutoMapper take existing values for me.
它会这样做吗? (我已经看过了,我可以看到的UseDestinationValue
的唯一示例涉及列表.它仅适用于列表吗?
Will it do that? (I have looked and the only examples I can see for UseDestinationValue
involve lists. Is it only for lists?
我能这样做吗?
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!只需运行它,看看.
I wrote this whole question up and then thought, DUH! just run it and see.
它如我所愿.
这是我最终得到的代码:
This is the code I ended up with:
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"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文