Automapper custom object

醉酒当歌 提交于 2019-12-12 06:38:54

问题


How I have configure automapper to map this:

class Source { Guid Id; double Price; }

To this:

class Destination { Guid Id; DestinationDifference Difference; }


class DestinationDifference { decimal Amount; }

回答1:


First: You should really read the FAQs on how to post a question and what information should be added. (No, I'm not the downvoter)

Here is an example how to get your mapping to work. Please note, that I've changed your classes a bit, because AutoMapper needs properties.

Source source = new Source();
source.Id = Guid.NewGuid();
source.Price = 10.0;

Mapper.Initialize(x => x.CreateMap<Source, Destination>()
    .ForMember(a => a.Difference,
        b => b.MapFrom(s => new DestinationDifference() { Amount = (decimal)s.Price })));

Destination destination = Mapper.Map<Source, Destination>(source);

Classes:

class Source
{
    public Guid Id { get; set; }
    public double Price { get; set; }
}

class Destination
{
    public Guid Id { get; set; }
    public DestinationDifference Difference { get; set; }
}

class DestinationDifference
{
    public decimal Amount { get; set; }
}


来源:https://stackoverflow.com/questions/45305965/automapper-custom-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!