What is AutoMapper?
AutoMapper is an object-object mapper. Object-object mapping works by transforming an input object of one type into an output object of a different type.
Why AutoMapper?
Suppose if our input object contains 20 properties then we need to write 20 lines of code for converting input object to destination object. Using AutoMapper, it will be done in less lines.
e.g.
Without AutoMapper.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using(var context = new EntityDBContext()) { var user = context.Users.Where(ID => ID.user_id == id).FirstOrDefault(); if (user != null) { userDto.UserId = user.user_id; userDto.Name = user.user_name; userDto.Address = user.user_address; userDto.PhoneNo = user.user_phoneNo; userDto.City = user.user_city; // more 20 lines of code } } |
With Mapper:
1 2 3 4 5 6 |
using(var context = new EntityDBContext()) { var user = context.Users.Where(ID => ID.user_id == id).FirstOrDefault(); Mapper.CreateMap<User,UserDto >(); userDto = Mapper.Map<User,UserDto >(user); } |
Note: Input and Destination object should have same property names.
The ForMember() method
Another important and useful method the AutoMapper provides is a ForMember() method. Suppose our dbContext class has two properties called FirstName and LastName whereas our model/viewmodel class has a property called FullName. Then we don’t need to create two extra properties in our model/viewmodel. We can use the ForMember() method for the mapping.
1 2 |
Mapper.CreateMap<User,UserDto>().ForMember(user => user.Fullname, map => map.MapFrom(p => p.FirstName + " " + p.LastName)); |
The Ignore() method
This method is useful when we have extra properties inside our destination object. This scenario is useful in ViewModel cases where we usually have extra properties. Then we can use the following:
1 2 3 |
Mapper.CreateMap<User,UserDto >() .ForMember(dt=>dt.SessionId,options=>options.Ignore()) .ForMember(dt=>dt.PROGRAM_NAME,options=>options.Ignore()); |
If you have any questions. please drop a comment 🙂