Automapper复杂对象

我已经开始实施这个;
Automapper映射到一个复杂的对象,但认为必须有更好的方法。

所以我创造了这个;

Mapper.CreateMap<StoreTransportWindow, CSVWindow>()
    .ForMember(dest => dest.DC, opt => opt.ResolveUsing(fa => fa.DC.number))
    .ForMember(dest => dest.Type, opt => opt.ResolveUsing(fa => fa.Type))
;

Mapper.CreateMap<Store, CSVStore>()
    .ForMember(dest => dest.StoreName, opt => opt.ResolveUsing(fa => fa.name))
    .ForMember(dest => dest.StoreNumber, opt => opt.ResolveUsing(fa => fa.number))
;

现在我想在主映射中使用上面的映射;

Mapper.CreateMap<Store, CSVLineObject>()
    .ForMember( dest => dest.store, opt => opt.ResolveUsing(/* This is where I'd like to use the above Store to  CSVStore mapping */)) 
;

这可能吗?

编辑

public class CSVStore
{
    public string StoreNumber { get; set; }
    public string StoreName { get; set; }
}

public class CSVWindow
{
    public string Type { get; set; }
    public string DC { get; set; }
    public string TPC { get; set; }

public class CSVLineObject
{
    public CSVStore store { get; set; }
    public List<CSVWindow> storeWindows { get; set; }

正如评论中提到的,最初的映射可能应该更像:

Mapper.CreateMap<StoreTransportWindow, CSVWindow>()
    .ForMember(dest => dest.DC, opt => opt.MapFrom(src => src.DC.number));
// Mapping for property Type not required

Mapper.CreateMap<Store, CSVStore>()
    .ForMember(dest => dest.StoreName, opt => opt.MapFrom(src => src.name))
    .ForMember(dest => dest.StoreNumber, opt => opt.MapFrom(src => src.number));

现在说你有以下几点:

public class Source
{
    public Store Store { get; set; }
}

public class Destination
{
    public CSVStore Store { get; set; }
}

那么下面的映射就足够了(因为你已经定义了嵌套映射StoreCSVStore ):

Mapper.CreateMap<Source, Destination>();

但是,如果Destination更像这样:

public class Destination
{
    public CSVStore CSVStore { get; set; }
}

然后,您需要显式定义要映射的属性:

Mapper.CreateMap<Source, Destination>()
    .ForMember(dest => dest.CSVStore, opt => opt.MapFrom(src => src.Store));

(请注意,从StoreCVStore的映射会自动应用。)

如果由于某种原因你确实需要明确定义一个嵌套映射,你可以这样做:

Mapper.CreateMap<Source, Destination>()
    .ForMember(dest => dest.destproperty,
               opt => opt.MapFrom(
                   src => Mapper.Map<SrcType, DestType>(src.srcproperty));

我有时需要使用它,但不是很经常,因为默认功能会自动为您处理。

如果您可以扩展您的需求,我可以提供更多详细信息。

链接地址: http://www.djcxy.com/p/6377.html

上一篇: Automapper complex objects

下一篇: Does it map lists of objects?