【问题标题】:Automapper custom objectAutomapper 自定义对象
【发布时间】:2017-07-25 14:16:05
【问题描述】:

我如何配置自动映射器来映射这个:

class Source { Guid Id; double Price; }

到这里:

class Destination { Guid Id; DestinationDifference Difference; }


class DestinationDifference { decimal Amount; }

【问题讨论】:

    标签: c# automapper


    【解决方案1】:

    首先:您应该认真阅读常见问题解答,了解如何发布问题以及应添加哪些信息。 (不,我不是反对者)

    这是一个如何让您的映射工作的示例。请注意,我已经稍微改变了你的类,因为 AutoMapper 需要属性。

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

    类:

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

    【讨论】:

    • AM 默认使用公共字段,您可以随时配置映射的内容。当然映射私有字段不是一个好主意:)
    猜你喜欢
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多