【问题标题】:Automapper map multiple dtos to the same modelAutomapper 将多个 dto 映射到同一个模型
【发布时间】:2012-10-26 17:07:55
【问题描述】:

我有一个模型,它是我的基础模型,其中包含许多字段。然后我有 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 个 dto(例如上面仅 2 个)放入同一个 _model 对象的最佳方法是什么?

【问题讨论】:

    标签: c# automapper dto


    【解决方案1】:

    每次以这种方式调用 Map 时,您都会要求 AutoMapper 创建一个新对象。您可以手动创建对象并使用Map&lt;TSource, TDestination&gt;(TSource source, TDestination destination) 来做您想做的事。例如:

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

    Mapper.Map(searchResultsQuery.BusinessDto, _model);
    

    【讨论】:

    • 谢谢。这就是我需要的。您也可以删除类型 Mapper.Map(searchResultsQuery.BusinessDto, _model);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多