Automapper complex objects

I've begun implementing this;
Automapper, mapping to a complex object but figured there must be a better way.

So I created this;

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

Now I'd like to use the above mappings in the primary map;

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

Is this possible?

edit

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

As mentioned in the comment, the initial mappings should probably be more like:

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

Now say you have the following:

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

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

Then the following mapping will suffice (as you've already defined the nested mapping Store to CSVStore ):

Mapper.CreateMap<Source, Destination>();

However if Destination was more like this:

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

Then you'll need to explicitly define the properties to be mapped:

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

(Note that the mapping from Store to CVStore is applied automatically.)

If for some reason you do need to explicitly define a nested mapping, you can do something like this:

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

I have needed to use that at times, but not very often as the default functionality takes care of it for you automatically.

I can provide more details if required if you can expand on your requirements.

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

上一篇: automapper将深层对象自动映射到平面对象并返回

下一篇: Automapper复杂对象