简体   繁体   中英

Automapper map to custom two object

I have got one generic list and I want to mapping this generic list to another type of generic list(BatchModel to Batch). But I have got some conditions before mapping two this object like that;

CrudTypes crudTypes(Enum)

List<BatchModel> batchModels;
             var models = batchModels.Select(p => new Batch
                {
                    BatchId = p.BatchId,
                    Id = p.Id,                   
                    CompleteTimeOnServer = crudTypes.Equals(CrudTypes.Insert) ? DateTime.Now : p.CompleteTimeOnServer,                    
                    SyncRetryCount = p.SyncRetryCount
                }).ToList();

How can I do this mapping in automapper ?

There's a way to do this, using BeforeMap in AutoMapper (see http://docs.automapper.org/en/stable/Before-and-after-map-actions.html ). Their own example:

Mapper.Initialize(cfg => { 
  cfg.CreateMap<Source, Dest>()
    .BeforeMap((src, dest) => src.Value = src.Value + 10)
    .AfterMap((src, dest) => dest.Name = "John");
});

And so you could rewrite this to extract the correct set (by your conditions) map as usual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM