2017-07-25 50 views
-1

如何我配置automapper映射这样的:Automapper自定义对象

class Source { Guid Id; double Price; } 

要这样:

class Destination { Guid Id; DestinationDifference Difference; } 


class DestinationDifference { decimal Amount; } 

回答

1

第一:你真的应该阅读如何张贴问题的常见问题和什么样的信息应该被添加。 (不,我不是downvoter)

下面是一个示例如何让您的映射工作。请注意,我已经改变了你的类,因为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; } 
} 
+0

AM工作在默认情况下与公共领域,你总是可以配置的内容被映射。当然映射私人领域不是一个好主意:) –