AutoMapper - Projections

So far we saw how to do mapping between simple objects that have same name and same type using AutoMapper. In the last post, I have explained the use of MapFrom method to do a custom mapping by concatnating values from two properties. In some case we may need to map properties between two fields with different property names and AutoMapper will be unable to do the mapping by default. Here also we are going to use the MapFrom method to determin which field needs to be picked up from the source for mapping the value in the destination object.

In the above example, we have different names for email field in source and destination classes. In the MapFrom method we are specifically directing to map the Email property in the source class with the PersonalEmail property in the destination class.

Now let's see how the mapping is done in complex objects. In the example given below, the Person class has got a composition Address class which holds all the address related info. Also we have view model called PersonVM which contains some properties from Person and Address classes.

So let's try to map the PersonVM class to Person class and see how it goes.

Again we are using lambda expressions on the right side to return a new instance of the Address object using the properties of address from the view model(PersonVM) to the destination instance(Person).


No Comments

Add a Comment