The document discusses object mapping using AutoMapper in .NET. It explains that Mapper is a class that maps properties between two objects. AutoMapper can automate this mapping process to avoid tedious manual mapping. It describes how to install and use AutoMapper by creating maps between source and destination objects and letting AutoMapper perform the mapping. It also discusses custom mappings, type conversions, null substitutions, projections and conditional mappings to handle complex mapping scenarios. The document concludes by explaining how to validate mappings using AutoMapper assertions.
2. What is a Mapper ?
• Mapper is a class or a function which maps the properties of two
objects.
• We generally get information to be processed through either a
service or from a database in the form of object.
• However it may happen that our Presentation Layer or in MVC’s
sense - “View” expects an input object which is of different form.
• So, a mapper is needed to map the properties of source object
(from DB or web service) to those of the destination object (which
will be supplied to View).
4. The AutoXMapper
Why Automate the mapping
process ?
• Manual Mapping process is
very tedious and time
consuming.
• Testing the mapping is even
more boring.
• Some times, no. of
properties to be mapped is
so large that chances of
manual errors are high.
AutoXMapper
• It’s an Object to Object
Mapper
• It comes as a DLL file
available with NuGet
Package in Visual Studio
2010/12/13
• Object of one type is
mapped to object of
another type
• Allows Loose coupling
5. Getting Started with AutoXMapper
• Install Nuget Package in Visual Studio. Automapper comes
with this package.
• After Installation, open Package Manager Console (comes
under Tools -> Library Package Manager ) and execute
following command:
PM> Install-Package AutoMapper
This command will add Automapper DLLs to your project and
also a reference to Automapper gets added automatically.
6. How to use AutoXMapper ?
1)
Prerequisites: Source and Destination Objects
a) Suppose, Source object is: objCustSource and
b) Destination object is: objCustDestination
2) Specifically in controller (For MVC application), write following code:
Mapper.CreateMap< objCustSourceType, objCustDestinationType >();
– This will create a map for the source and destination type objects. We
here register the source and destination objects for mapping.
objCustomerDestinationType objCustDestination = Mapper.Map<
objCustSourceType, objCustDestinationType >(objCustSource);
– This will perform the actual mapping
7. How to use AutoXMapper ?
• So, just these two lines will create an entire one to one mapping
between the source and destination properties of the
corresponding objects. Loads of lines of code is saved and lot of
efforts too!
• Word of caution : The corresponding properties of source and
destination objects should have similar naming structure.
– For e.g. The property in the objDestination to be mapped with
objSource.CustomerName should have name as ‘CustomerName’ only. If we
give name as CustomerFullName instead of CustomerName in objDestination,
the automapper will not recognise it.
8. Let us understand how to use the
AutoXMapper practically in a MVC
Application…
9. Model Class - Customer
Customer View Class – Its object
will be supplied to View
10. CustomerController:
Object of Cusomer Class is
mapped with object of
CustomerView Class through
AutoXmapper.
The newly formed object of
CustomerView is passed to
the view.
11. Strongly typed view is created and properties of class CustomerView are
directly accessed in the View – Index.aspx
13. What would we have done if we
hadn’t used AutoXMapper ?
We had to map the properties
of these two objects manually…
Boring Lines of Code…
If there were 30 such
properties, we would have to
write 30 such lines…!!!
15. We may face several problems while using
AutoXmapper. For example, we want to
make custom calculations with the
properties while mapping. How will that
be taken care of by AutoXmapper ?
16. Custom Value Resolvers
•
•
Although AutoXMapper covers quite a few destination member mapping
scenarios, there are the 1 to 5% of destination values that need a little help in
resolving.
For example, we might want to have a calculated value just during the
mapping:
public class Source
{
public int Value1 { get; set; }
public int Value2 { get; set; }
}
public class Destination
{
public int Total { get; set; }
}
17. Custom Value Resolvers
• For whatever reason, we want Total to be the sum of the source
Value properties. This can be achieved with the help of Custom
Value Resolver.
public class CustomResolver : ValueResolver<Source, int>
{
protected override int ResolveCore(Source source)
{
return source.Value1 + source.Value2;
}
}
18. Custom Value Resolvers
• Now we’ll need to tell AutoMapper to use this custom value
resolver when resolving a specific destination member.
Mapper.CreateMap<Source, Destination>()
.ForMember(dest => dest.Total, opt =>
opt.ResolveUsing<CustomResolver>());
19. Data types of properties being mapped are
different… How to handle such scenarios ?
20. Custom Type Converters
•
•
There are several scenarios in which we need to convert one type in to other in
mapping.
For example:
public class Source
{
public string Value1 { get; set; }
public string Value2 { get; set; }
public string Value3 { get; set; }
}
public class Destination
{
public int Value1 { get; set; }
public DateTime Value2 { get; set; }
public Type Value3 { get; set; }
}
21. Custom Type Converters
• If we were to try and map these two types as-is, AutoMapper would throw
an exception (at map time and configuration-checking time), as
AutoMapper does not know about any mapping from string to int,
DateTime or Type.
• To create maps for these types, we must supply a custom type converter
as follows in 3 simple steps:
1) Create an Interface for custom type converting:
public interface ITypeConverter<TSource, TDestination>
{
TDestination Convert(ResolutionContext context);
}
22. Custom Type Converters
2) Create specific type converter classes which will implement the interface.
public class DateTimeTypeConverter : ITypeConverter<string, DateTime>
{
public DateTime Convert(ResolutionContext context)
{
return System.Convert.ToDateTime(context.SourceValue);
}
}
public class TypeTypeConverter : ITypeConverter<string, Type>
{
public Type Convert(ResolutionContext context)
{
return context.SourceType;
}
}
23. Custom Type Converters
3) And supply AutoMapper with either an instance of a custom type
converter, or simply the type, which AutoMapper will instantiate at run time.
The mapping configuration for our above source/destination types then
becomes:
public void Example()
{ Mapper.CreateMap<string, int>().ConvertUsing(Convert.ToInt32);
Mapper.CreateMap<string, DateTime>().ConvertUsing(new
DateTimeTypeConverter());
Mapper.CreateMap<string, Type>().ConvertUsing<TypeTypeConverter>();
Mapper.CreateMap<Source, Destination>();
}
24. Some of the properties being mapped
are null… What to do ???
25. Null Substitutions
Null substitution allows you to supply an alternate value for a
destination member if the source value is null anywhere along the
member chain.
This can be done in following way:
Mapper.CreateMap<Source, Dest>()
.ForMember(dest => dest.Value, opt => opt.NullSubstitute("Other
Value"));
26. Source and Destination properties’ structure
is different… Can AutoXmapper resolve that ?
27. Projections
When you want to project source values into a destination that does
not exactly match the source structure, you must specify custom
member mapping definitions. For example, we might want to turn this
source structure:
public class CalendarEvent
{
public DateTime Date { get; set; }
public string Title { get; set; }
}
28. Projections
Into something that works better for an input form on a web page:
public class CalendarEventForm
{
public DateTime EventDate { get; set; }
public int EventHour { get; set; }
public int EventMinute { get; set; }
public string Title { get; set; }
}
29. Projections
• Because the names of the destination properties do not
exactly match up to the source property (CalendarEvent.Date
would need to be CalendarEventForm.EventDate), we need to
specify custom member mappings in our type map
configuration.
• Here, we can make use of the MapFrom option to perform
custom source/destination member mappings. The MapFrom
method takes a lambda expression as a parameter, which
then is evaluated later during mapping.
31. Don’t want to perform the mapping
straight a way… Can AutoXmapper
help putting some conditions ?
32. Conditional Mapping
• AutoMapper allows us to add conditions to properties that
must be met before that property will be mapped.
• This can be used in situations like the following where we are
trying to map from an int to an unsigned int.
class A
{
int x;
}
class B
{
uint x;
}
33. Conditional Mapping
• In the following mapping the property baz will only be mapped if it
is greater then or equal to 0 in the source object.
Mapper.CreateMap<A,B>()
.ForMember(dest => dest.x, opt => opt.Condition(src => (src.x >= 0));
35. Validating Mappings
• To test your mappings, you need to create a test that does two
things:
a) Call your bootstrapper class to create all the mappings
b) Call Mapper.AssertConfigurationIsValid
With just these two lines of code, all the mapping done is validated.
Bootstrapper.ConfigureAutomapper();
Mapper.AssertConfigurationIsValid();
36. Validating Mappings
• The ConfigureAutoMapper Method present in the Bootstrapper
Class, which contains all the mappings done using Automapper:
38. Platforms Supported
AutoMapper supports the following platforms:
•
•
•
•
.NET 4 and higher
Silverlight 4 and higher
Windows Phone 7.5 and higher
.NET for Windows Store apps (WinRT)