SlideShare una empresa de Scribd logo
1 de 39
Descargar para leer sin conexión
- Krantisinh Deshmukh
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).
Object for View: customerView
Object for Model: customerModel

Mannual Mapping:

Traditional
Mapping

• customerView.FirstName =
customerModel.FirstName
• customerView.LastName =
customerModel.LstName
• customerView.MiddleName =
customerModel.MidName
• customerView.DateofBirth =
customerModel.DateOB
• customerView.Address =
customerModel.Address
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
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.
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
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.
Let us understand how to use the
AutoXMapper practically in a MVC
Application…
Model Class - Customer

Customer View Class – Its object
will be supplied to View
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.
Strongly typed view is created and properties of class CustomerView are
directly accessed in the View – Index.aspx
And the output is:
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…!!!
Is that All ??? Definitely not…
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 ?
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; }
}
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;
}
}
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>());
Data types of properties being mapped are
different… How to handle such scenarios ?
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; }
}
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);
}
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;
}
}
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>();
}
Some of the properties being mapped
are null… What to do ???
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"));
Source and Destination properties’ structure
is different… Can AutoXmapper resolve that ?
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; }
}
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; }
}
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.
// Model
var calendarEvent = new CalendarEvent
{
EventDate = new DateTime(2008, 12, 15, 20, 30, 0),
Title = "Company Holiday Party"
};
// Configure AutoMapper
Mapper.CreateMap<CalendarEvent, CalendarEventForm>()
.ForMember(dest => dest.EventDate, opt => opt.MapFrom(src
=> src.EventDate.Date))
.ForMember(dest => dest.EventHour, opt => opt.MapFrom(src
=> src.EventDate.Hour))
.ForMember(dest => dest.EventMinute, opt =>
opt.MapFrom(src => src.EventDate.Minute));

// Perform mapping
CalendarEventForm form = Mapper.Map<CalendarEvent,
CalendarEventForm>(calendarEvent);
Don’t want to perform the mapping
straight a way… Can AutoXmapper
help putting some conditions ?
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;
}
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));
Done with Mapping ??? How to
Validate?
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();
Validating Mappings
• The ConfigureAutoMapper Method present in the Bootstrapper
Class, which contains all the mappings done using Automapper:
Validating Mappings
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)
Thank You

Más contenido relacionado

La actualidad más candente

Client side scripting using Javascript
Client side scripting using JavascriptClient side scripting using Javascript
Client side scripting using Javascript
Bansari Shah
 
Menu bars and menus
Menu bars and menusMenu bars and menus
Menu bars and menus
myrajendra
 

La actualidad más candente (20)

Lezione 8: Introduzione ai Web Service
Lezione 8: Introduzione ai Web ServiceLezione 8: Introduzione ai Web Service
Lezione 8: Introduzione ai Web Service
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency Injection
 
Exception handling
Exception handlingException handling
Exception handling
 
Client side scripting using Javascript
Client side scripting using JavascriptClient side scripting using Javascript
Client side scripting using Javascript
 
Day02 a pi.
Day02   a pi.Day02   a pi.
Day02 a pi.
 
Rest API with Swagger and NodeJS
Rest API with Swagger and NodeJSRest API with Swagger and NodeJS
Rest API with Swagger and NodeJS
 
React Class Components vs Functional Components: Which is Better?
React Class Components vs Functional Components: Which is Better?React Class Components vs Functional Components: Which is Better?
React Class Components vs Functional Components: Which is Better?
 
Introduction to SOAP
Introduction to SOAPIntroduction to SOAP
Introduction to SOAP
 
Protege tutorial
Protege tutorialProtege tutorial
Protege tutorial
 
Support formation vidéo: Android Kotlin : développez des applications mobiles
Support formation vidéo: Android Kotlin : développez des applications mobiles Support formation vidéo: Android Kotlin : développez des applications mobiles
Support formation vidéo: Android Kotlin : développez des applications mobiles
 
ORDS - Oracle REST Data Services
ORDS - Oracle REST Data ServicesORDS - Oracle REST Data Services
ORDS - Oracle REST Data Services
 
EJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another IntroductionEJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another Introduction
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
Bean Validation - Cours v 1.1
Bean Validation - Cours v 1.1Bean Validation - Cours v 1.1
Bean Validation - Cours v 1.1
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServices
 
Share preference
Share preferenceShare preference
Share preference
 
Menu bars and menus
Menu bars and menusMenu bars and menus
Menu bars and menus
 
Be a Hero on Day 1 with ASP.Net Boilerplate
Be a Hero on Day 1 with ASP.Net BoilerplateBe a Hero on Day 1 with ASP.Net Boilerplate
Be a Hero on Day 1 with ASP.Net Boilerplate
 

Similar a Automapper

Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
AOE
 
Accumulo Summit 2016: Introducing Accumulo Collections: A Practical Accumulo ...
Accumulo Summit 2016: Introducing Accumulo Collections: A Practical Accumulo ...Accumulo Summit 2016: Introducing Accumulo Collections: A Practical Accumulo ...
Accumulo Summit 2016: Introducing Accumulo Collections: A Practical Accumulo ...
Accumulo Summit
 
Hadoop_Pennonsoft
Hadoop_PennonsoftHadoop_Pennonsoft
Hadoop_Pennonsoft
PennonSoft
 
Embedded Mirror Maker
Embedded Mirror MakerEmbedded Mirror Maker
Embedded Mirror Maker
Simon Suo
 
16 auto mapper
16 auto mapper16 auto mapper
16 auto mapper
rbrmameli
 

Similar a Automapper (20)

MVC Puree - Approaches to MVC with Umbraco
MVC Puree - Approaches to MVC with UmbracoMVC Puree - Approaches to MVC with Umbraco
MVC Puree - Approaches to MVC with Umbraco
 
NET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxNET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptx
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Hadoop map reduce in operation
Hadoop map reduce in operationHadoop map reduce in operation
Hadoop map reduce in operation
 
Accumulo Summit 2016: Introducing Accumulo Collections: A Practical Accumulo ...
Accumulo Summit 2016: Introducing Accumulo Collections: A Practical Accumulo ...Accumulo Summit 2016: Introducing Accumulo Collections: A Practical Accumulo ...
Accumulo Summit 2016: Introducing Accumulo Collections: A Practical Accumulo ...
 
Aggregating In Accumulo
Aggregating In AccumuloAggregating In Accumulo
Aggregating In Accumulo
 
Hadoop_Pennonsoft
Hadoop_PennonsoftHadoop_Pennonsoft
Hadoop_Pennonsoft
 
iOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsiOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIs
 
Embedded Mirror Maker
Embedded Mirror MakerEmbedded Mirror Maker
Embedded Mirror Maker
 
Hadoop - Introduction to mapreduce
Hadoop -  Introduction to mapreduceHadoop -  Introduction to mapreduce
Hadoop - Introduction to mapreduce
 
Map reduce in Hadoop BIG DATA ANALYTICS
Map reduce in Hadoop BIG DATA ANALYTICSMap reduce in Hadoop BIG DATA ANALYTICS
Map reduce in Hadoop BIG DATA ANALYTICS
 
Scalding big ADta
Scalding big ADtaScalding big ADta
Scalding big ADta
 
Elements for an iOS Backend
Elements for an iOS BackendElements for an iOS Backend
Elements for an iOS Backend
 
16 auto mapper
16 auto mapper16 auto mapper
16 auto mapper
 
16 auto mapper
16 auto mapper16 auto mapper
16 auto mapper
 
Map reduce
Map reduceMap reduce
Map reduce
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Php Map Script Class Reference
Php Map Script Class ReferencePhp Map Script Class Reference
Php Map Script Class Reference
 
Relevance trilogy may dream be with you! (dec17)
Relevance trilogy  may dream be with you! (dec17)Relevance trilogy  may dream be with you! (dec17)
Relevance trilogy may dream be with you! (dec17)
 

Último

Último (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

Automapper

  • 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).
  • 3. Object for View: customerView Object for Model: customerModel Mannual Mapping: Traditional Mapping • customerView.FirstName = customerModel.FirstName • customerView.LastName = customerModel.LstName • customerView.MiddleName = customerModel.MidName • customerView.DateofBirth = customerModel.DateOB • customerView.Address = customerModel.Address
  • 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…!!!
  • 14. Is that All ??? Definitely not…
  • 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.
  • 30. // Model var calendarEvent = new CalendarEvent { EventDate = new DateTime(2008, 12, 15, 20, 30, 0), Title = "Company Holiday Party" }; // Configure AutoMapper Mapper.CreateMap<CalendarEvent, CalendarEventForm>() .ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.EventDate.Date)) .ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.EventDate.Hour)) .ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.EventDate.Minute)); // Perform mapping CalendarEventForm form = Mapper.Map<CalendarEvent, CalendarEventForm>(calendarEvent);
  • 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));
  • 34. Done with Mapping ??? How to Validate?
  • 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)