简体   繁体   中英

Automapper - Creating Maps in C#

Was just getting started with AutoMapper and wanted to get clarity on something.

Let's say I want to seamlessly map between a User and a 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:

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? 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 :

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

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