Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper: Update property values without creating a new object

How can I use automapper to update the properties values of another object without creating a new one?

like image 352
ryudice Avatar asked Mar 03 '10 20:03

ryudice


People also ask

Why you should not use AutoMapper?

1. If you use the convention-based mapping and a property is later renamed that becomes a runtime error and a common source of annoying bugs. 2. If you don't use convention-based mapping (ie you explicitly map each property) then you are just using automapper to do your projection, which is unnecessary complexity.

How do I ignore property mapping in AutoMapper?

So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored property could be in either the source or the destination object.

Should I use AutoMapper or not?

If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.


2 Answers

Use the overload that takes the existing destination:

Mapper.Map<Source, Destination>(source, destination); 

Yes, it returns the destination object, but that's just for some other obscure scenarios. It's the same object.

like image 127
Jimmy Bogard Avatar answered Oct 08 '22 04:10

Jimmy Bogard


To make this work you have to CreateMap for types of source and destination even they are same type. That means if you want to Mapper.Map<User, User>(user1, user2); You need to create map like this Mapper.Create<User, User>()

like image 43
Flux Xu Avatar answered Oct 08 '22 04:10

Flux Xu