AutoMapper和“UseDestinationValue”

时间:2011-08-16 20:08:37

标签: automapper

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?

2 个答案:

答案 0 :(得分:3)

我把整个问题写完了然后想了想,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; }
}

输出结果为:

  

罗伯特
  丹
  罗伯特
  丹

答案 1 :(得分:2)

我被带到这里有类似的问题,但关于嵌套类和保持目标值。我以任何方式尝试过,但它对我不起作用,事实证明你必须在父对象上使用UseDestinationValue。我要离开这里,以防其他人遇到同样的问题。我花了一些时间才能让它运转起来。我一直认为问题在于AddressViewModel =&gt;地址映射。

在BidderViewModel类中,BidderAddress的类型为AddressViewModel。我需要在非空的情况下保留地址ID。

Mapper.CreateMap<BidderViewModel, Bidder>()
    .ForMember(dest => dest.BidderAddress, opt=> opt.UseDestinationValue())
    .ForMember(dest => dest.ID, opt => opt.UseDestinationValue());
Mapper.CreateMap<AddressViewModel, Address>()
    .ForMember(dest => dest.ID, opt => { opt.UseDestinationValue(); opt.Ignore(); });

使用(其中viewModel的类型为BidderViewModel,由MVC中的View返回):

Bidder bidder = Mapper.Map<BidderViewModel, Bidder>(viewModel, currentBid.Bidder)