自动化复杂对象

时间:2013-04-19 01:32:38

标签: c# automapper

我已经开始实施这个;
Automapper, mapping to a complex object但我认为必须有更好的方法。

所以我创造了这个;

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

1 个答案:

答案 0 :(得分:0)

正如评论中所提到的,初始映射应该更像是:

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

然后,以下映射就足够了(因为您已经将嵌套映射Store定义为CSVStore):

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

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

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