简体   繁体   English

Automapper-在C#中创建地图

[英]Automapper - Creating Maps in C#

Was just getting started with AutoMapper and wanted to get clarity on something. 刚开始使用AutoMapper并想使某些事情变得清晰。

Let's say I want to seamlessly map between a User and a UserDto. 假设我要在User和UserDto之间无缝映射。

The examples all seem to suggest that I must first go to a startup area (for example WebApiConfig.cs or startup.cs or global.axax etc) and do something like this: 这些示例似乎都建议我必须先进入启动区域(例如WebApiConfig.cs或startup.cs或global.axax等),然后执行以下操作:

Mapper.CreateMap<User, UserDto>();

Presumably if I had 50 or 100 entities/DTOs that I wanted to map, I would need to literally add 50 or 100 lines of code with mappings between one class to another? 大概如果我有50或100个要映射的实体/ DTO,我是否真的需要添加50或100行代码以及一类到另一类之间的映射? Surely there's a smarter way, right? 当然有更聪明的方法了吧?

If I don't ever need to do any specific mapping / overriding, do I really need to do this? 如果我不需要进行任何特定的映射/覆盖,是否真的需要这样做? I must have misunderstood the fundamentals of the framework because that just seems wrong to me. 我一定误解了框架的基础,因为这对我来说似乎是错误的。

Thanks! 谢谢!

As long as everything matches up on the source and the target, you could use DynamicMap : 只要源和目标上的所有内容都匹配,就可以使用DynamicMap

var target = Mapper.DynamicMap<TSource, TTarget>(source);

However it would be more efficient to create a mapping as required: 但是,根据需要创建映射会更有效:

if (Mapper.FindTypeMapFor<TSource, TTarget>() == null)
{
    Mapper.CreateMap<TSource, TTarget>();
}

var target =  Mapper.Map<TSource, TTarget>(source);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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