Automapper将多个dtos映射到同一模型

时间:2012-10-26 17:07:55

标签: c# automapper dto

我的模型是我的基础模型,其中包含许多字段。然后我有4个DTO,它们是该模型的一部分。我想最后将它们全部映射到模型,但每次映射都会覆盖以前的映射。

例如

_model = new GenericModel();
_model.ExampleNotInDTO = "This Gets Overwritten being set previously";

//First Mapping below overwrites the property I set above and 
// sets only the fields in the business dto.
Mapper.CreateMap<BusinessDto, GenericModel>();
_model = Mapper.Map<BusinessDto, GenericModel>(searchResultsQuery.BusinessDto);

//Now doing another mapping just below it nulls out all the previous 
// stuff and only fills in the events dto.
Mapper.CreateMap<EventsDto, GenericModel>();
_model = Mapper.Map<EventsDto, GenericModel>(searchResultsQuery.EventsDto);

如何将所有4个dtos(例如只有2个以上)用于同一个_model对象的最佳方法是什么?

1 个答案:

答案 0 :(得分:4)

每次以这种方式调用Map时,您都要求AutoMapper创建一个新对象。您可以手动创建对象,并使用Map<TSource, TDestination>(TSource source, TDestination destination)执行您想要的操作。例如:

Mapper.Map<BusinessDto, GenericModel>(searchResultsQuery.BusinessDto, _model);

Mapper.Map(searchResultsQuery.BusinessDto, _model);