SlideShare ist ein Scribd-Unternehmen logo
1 von 17
AutoMapper
- RUCHIR SHAH
What is AutoMapper?
 AutoMapper is a simple little library built to solve a deceptively complex
problem - getting rid of code that mapped one object to another.
 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.
 What makes AutoMapper interesting is that it provides some interesting
conventions to take the dirty work out of figuring out how to map type A
to type B.
 As long as type B follows AutoMapper's established convention, almost
zero configuration is needed to map two types.
Why use AutoMapper?
 Mapping code is boring. Testing mapping code is even more boring.
AutoMapper provides simple configuration of types, as well as simple
testing of mappings.
 The real question may be "why use object-object mapping?" Mapping can
occur in many places in an application, but mostly in the boundaries
between layers, such as between the UI/Domain layers, or Service/Domain
layers.
 The mapper is needed to map properties of source object (from DB or web
service) to those of the destination object (which will supplied to view).
 Concerns of one layer often conflict with concerns in another, so object-
object mapping leads to segregated models, where concerns for each layer
can affect only types in that layer.
Why use AutoMapper?
 Challenge: Sometimes while interacting with real time (database) entities
and binding our model to them, we end up in a situation like:
Why use AutoMapper?
 Resolution: What makes AutoMapper interesting is that it provides some
interesting conventions to take the dirty work out of figuring out how to
map type A to type B. As long as type B follows AutoMapper's established
conventions, almost zero configuration is needed to map two types."
Therefore, it provides the solution for our mapping issue.
How do I get started?
 Firstly install the NuGet Package Manager in your Visual Studio IDE. Once
done, go to:
 Tools -> Library Packet Manager -> Packet manager Console
 Then in the console window opened at the bottom of Visual Studio, type:
 PM> Install-Package AutoMapper
How do I use AutoMapper?
 AutoMapper works best as long as the names of the members match up to
the source type's members. If you have a source member called
"FirstName", this will automatically be mapped to a destination member
with the name "FirstName".
 AutoMapper will ignore null reference exceptions when mapping your
source to your target. This is by design. If you don't like this approach, you
can combine AutoMapper's approach with Custom-value-resolvers if
needed.
How do I use AutoMapper?
 Once you have your types you can create a map for the two types using
Mapper.Initialize and CreateMap. Mapper.Initialize should be called only
once during startup.
 The type on the left is the source type, and the type on the right is the
destination type. To perform a mapping, use the Map method.
 AutoMapper also has non-generic versions of these methods, for those
cases where you might not know the type at compile time.
Where will AutoMapper fit in here?
Where will AutoMapper fit in here?
 It will be used to replace the property mapping done one by one in the
code, therefore, at the first line of code, define an AutoMap. To create the
default mapping, callMapper.CreateMap<T1, T2>() with proper types.
 LearningMVC.User -> DTO Object Class
 LearningMVC.Models.User -> Model Class to bind the View
 here we define a mapping between DTO and the Model class with the help
of the AutoMapper class.
Where will AutoMapper fit in here?
 Now inside the foreach loop, replace the whole code by:
 Finally call the Mapper.Map<T1, T2>(obj1) to get the mapped object of T2.
Final code using AutoMapper
General Features
 Before and after map actions
 Containers
 Mapping Inheritance
 Queryable Extensions (LINQ)
 Configuration
 Conditional Mapping
 Open Generics
 Flattening
 Projection
 Configuration Validation
 Lists and Arrays
 Nested Mappings
 Custom Type Converters
 Custom Value Resolvers
 Null Substitution
Projection
 Projection transforms a source to a destination beyond flattening the
object model. Without extra configuration, AutoMapper requires a
flattened destination to match the source type's naming structure.
 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.
Projection
 For example, we might want to turn this source structure:
 Into something that works better for an input form on a web page:
Projection
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:
Projection
 ForMember() and MapFrom() in AutoMapper Two important functions in
AutoMapper play an important role in object mapping.
 Suppose our model/viewmodel class has a property FullName, and from
the DTO we want to add the First Name and Last Name of the user to
make it a full name and bind it to the model. For these kinds of scenarios
ForMember() andMapFrom() come in handy.
 Here we are saying that ForMember FullName in our model class maps
properties from FirstName andLastName of User DTO.

Weitere ähnliche Inhalte

Was ist angesagt? (20)

React&redux
React&reduxReact&redux
React&redux
 
Introduction to .NET Framework
Introduction to .NET FrameworkIntroduction to .NET Framework
Introduction to .NET Framework
 
Ef code first
Ef code firstEf code first
Ef code first
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
ASP.NET Routing & MVC
ASP.NET Routing & MVCASP.NET Routing & MVC
ASP.NET Routing & MVC
 
Expressjs
ExpressjsExpressjs
Expressjs
 
Refactoring
RefactoringRefactoring
Refactoring
 
Object-Oriented Programming Concepts
Object-Oriented Programming ConceptsObject-Oriented Programming Concepts
Object-Oriented Programming Concepts
 
React
ReactReact
React
 
Typescript in 30mins
Typescript in 30mins Typescript in 30mins
Typescript in 30mins
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Oops ppt
Oops pptOops ppt
Oops ppt
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 
React lecture
React lectureReact lecture
React lecture
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
Entity Framework Core
Entity Framework CoreEntity Framework Core
Entity Framework Core
 

Andere mochten auch

Andere mochten auch (9)

How Volkswagen Dynamic Chassis Control Works
How Volkswagen Dynamic Chassis Control WorksHow Volkswagen Dynamic Chassis Control Works
How Volkswagen Dynamic Chassis Control Works
 
Santhosh kumar gattu
Santhosh kumar gattuSanthosh kumar gattu
Santhosh kumar gattu
 
Oral presentation speaking
Oral presentation  speakingOral presentation  speaking
Oral presentation speaking
 
Johnathan Cody Massey new resume
Johnathan Cody Massey new resumeJohnathan Cody Massey new resume
Johnathan Cody Massey new resume
 
MercerFX
MercerFXMercerFX
MercerFX
 
Mon futur professionel
Mon futur professionelMon futur professionel
Mon futur professionel
 
Laila tugas blog1
Laila tugas blog1Laila tugas blog1
Laila tugas blog1
 
Report On HMS
Report On HMSReport On HMS
Report On HMS
 
An Alternate religion
An Alternate religionAn Alternate religion
An Alternate religion
 

Ähnlich wie AutoMapper

AutoCAD Tips, Tricks, and Delightful Drafting Techniques
AutoCAD Tips, Tricks, and Delightful Drafting TechniquesAutoCAD Tips, Tricks, and Delightful Drafting Techniques
AutoCAD Tips, Tricks, and Delightful Drafting TechniquesDonnie Gladfelter
 
FME: Not Just for ETL
FME: Not Just for ETLFME: Not Just for ETL
FME: Not Just for ETLSafe Software
 
Hadoop interview questions - Softwarequery.com
Hadoop interview questions - Softwarequery.comHadoop interview questions - Softwarequery.com
Hadoop interview questions - Softwarequery.comsoftwarequery
 
Publishing geoprocessing-services-tutorial
Publishing geoprocessing-services-tutorialPublishing geoprocessing-services-tutorial
Publishing geoprocessing-services-tutorialSebastian Correa Gimenez
 
Maths&programming forartists wip
Maths&programming forartists wipMaths&programming forartists wip
Maths&programming forartists wipkedar nath
 
Annotation tools for ADAS & Autonomous Driving
Annotation tools for ADAS & Autonomous DrivingAnnotation tools for ADAS & Autonomous Driving
Annotation tools for ADAS & Autonomous DrivingYu Huang
 
Utilizing Layers in AutoCAD Prototype Package
Utilizing Layers in AutoCAD Prototype PackageUtilizing Layers in AutoCAD Prototype Package
Utilizing Layers in AutoCAD Prototype PackageBrian Mitchell
 
Android app material design from dev's perspective
Android app material design from dev's perspectiveAndroid app material design from dev's perspective
Android app material design from dev's perspectiveDeSmart Agile Software House
 
Design Patterns By Sisimon Soman
Design Patterns By Sisimon SomanDesign Patterns By Sisimon Soman
Design Patterns By Sisimon SomanSisimon Soman
 
Best Practices for Shader Graph
Best Practices for Shader GraphBest Practices for Shader Graph
Best Practices for Shader GraphUnity Technologies
 
Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1LK394
 
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...ICS
 
Java files and io streams
Java files and io streamsJava files and io streams
Java files and io streamsRubaNagarajan
 
5 Ways to Improve Your LiDAR Workflows
5 Ways to Improve Your LiDAR Workflows5 Ways to Improve Your LiDAR Workflows
5 Ways to Improve Your LiDAR WorkflowsSafe Software
 
Ary Mouse for Image Processing
Ary Mouse for Image ProcessingAry Mouse for Image Processing
Ary Mouse for Image ProcessingIJERA Editor
 

Ähnlich wie AutoMapper (20)

Programming with Mathcad Prime
Programming with Mathcad PrimeProgramming with Mathcad Prime
Programming with Mathcad Prime
 
AutoCAD Tips, Tricks, and Delightful Drafting Techniques
AutoCAD Tips, Tricks, and Delightful Drafting TechniquesAutoCAD Tips, Tricks, and Delightful Drafting Techniques
AutoCAD Tips, Tricks, and Delightful Drafting Techniques
 
FME: Not Just for ETL
FME: Not Just for ETLFME: Not Just for ETL
FME: Not Just for ETL
 
Hadoop interview questions - Softwarequery.com
Hadoop interview questions - Softwarequery.comHadoop interview questions - Softwarequery.com
Hadoop interview questions - Softwarequery.com
 
Publishing geoprocessing-services-tutorial
Publishing geoprocessing-services-tutorialPublishing geoprocessing-services-tutorial
Publishing geoprocessing-services-tutorial
 
Matlab demo
Matlab demoMatlab demo
Matlab demo
 
Maths&programming forartists wip
Maths&programming forartists wipMaths&programming forartists wip
Maths&programming forartists wip
 
Annotation tools for ADAS & Autonomous Driving
Annotation tools for ADAS & Autonomous DrivingAnnotation tools for ADAS & Autonomous Driving
Annotation tools for ADAS & Autonomous Driving
 
Utilizing Layers in AutoCAD Prototype Package
Utilizing Layers in AutoCAD Prototype PackageUtilizing Layers in AutoCAD Prototype Package
Utilizing Layers in AutoCAD Prototype Package
 
Praseed Pai
Praseed PaiPraseed Pai
Praseed Pai
 
Android app material design from dev's perspective
Android app material design from dev's perspectiveAndroid app material design from dev's perspective
Android app material design from dev's perspective
 
Design Patterns By Sisimon Soman
Design Patterns By Sisimon SomanDesign Patterns By Sisimon Soman
Design Patterns By Sisimon Soman
 
Best Practices for Shader Graph
Best Practices for Shader GraphBest Practices for Shader Graph
Best Practices for Shader Graph
 
Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1
 
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
 
Design Patern::Adaptor pattern
Design Patern::Adaptor patternDesign Patern::Adaptor pattern
Design Patern::Adaptor pattern
 
Java files and io streams
Java files and io streamsJava files and io streams
Java files and io streams
 
5 Ways to Improve Your LiDAR Workflows
5 Ways to Improve Your LiDAR Workflows5 Ways to Improve Your LiDAR Workflows
5 Ways to Improve Your LiDAR Workflows
 
newappsonbaseinnovtions
newappsonbaseinnovtionsnewappsonbaseinnovtions
newappsonbaseinnovtions
 
Ary Mouse for Image Processing
Ary Mouse for Image ProcessingAry Mouse for Image Processing
Ary Mouse for Image Processing
 

Kürzlich hochgeladen

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 

Kürzlich hochgeladen (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

AutoMapper

  • 2. What is AutoMapper?  AutoMapper is a simple little library built to solve a deceptively complex problem - getting rid of code that mapped one object to another.  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.  What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B.  As long as type B follows AutoMapper's established convention, almost zero configuration is needed to map two types.
  • 3. Why use AutoMapper?  Mapping code is boring. Testing mapping code is even more boring. AutoMapper provides simple configuration of types, as well as simple testing of mappings.  The real question may be "why use object-object mapping?" Mapping can occur in many places in an application, but mostly in the boundaries between layers, such as between the UI/Domain layers, or Service/Domain layers.  The mapper is needed to map properties of source object (from DB or web service) to those of the destination object (which will supplied to view).  Concerns of one layer often conflict with concerns in another, so object- object mapping leads to segregated models, where concerns for each layer can affect only types in that layer.
  • 4. Why use AutoMapper?  Challenge: Sometimes while interacting with real time (database) entities and binding our model to them, we end up in a situation like:
  • 5. Why use AutoMapper?  Resolution: What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B. As long as type B follows AutoMapper's established conventions, almost zero configuration is needed to map two types." Therefore, it provides the solution for our mapping issue.
  • 6. How do I get started?  Firstly install the NuGet Package Manager in your Visual Studio IDE. Once done, go to:  Tools -> Library Packet Manager -> Packet manager Console  Then in the console window opened at the bottom of Visual Studio, type:  PM> Install-Package AutoMapper
  • 7. How do I use AutoMapper?  AutoMapper works best as long as the names of the members match up to the source type's members. If you have a source member called "FirstName", this will automatically be mapped to a destination member with the name "FirstName".  AutoMapper will ignore null reference exceptions when mapping your source to your target. This is by design. If you don't like this approach, you can combine AutoMapper's approach with Custom-value-resolvers if needed.
  • 8. How do I use AutoMapper?  Once you have your types you can create a map for the two types using Mapper.Initialize and CreateMap. Mapper.Initialize should be called only once during startup.  The type on the left is the source type, and the type on the right is the destination type. To perform a mapping, use the Map method.  AutoMapper also has non-generic versions of these methods, for those cases where you might not know the type at compile time.
  • 9. Where will AutoMapper fit in here?
  • 10. Where will AutoMapper fit in here?  It will be used to replace the property mapping done one by one in the code, therefore, at the first line of code, define an AutoMap. To create the default mapping, callMapper.CreateMap<T1, T2>() with proper types.  LearningMVC.User -> DTO Object Class  LearningMVC.Models.User -> Model Class to bind the View  here we define a mapping between DTO and the Model class with the help of the AutoMapper class.
  • 11. Where will AutoMapper fit in here?  Now inside the foreach loop, replace the whole code by:  Finally call the Mapper.Map<T1, T2>(obj1) to get the mapped object of T2.
  • 12. Final code using AutoMapper
  • 13. General Features  Before and after map actions  Containers  Mapping Inheritance  Queryable Extensions (LINQ)  Configuration  Conditional Mapping  Open Generics  Flattening  Projection  Configuration Validation  Lists and Arrays  Nested Mappings  Custom Type Converters  Custom Value Resolvers  Null Substitution
  • 14. Projection  Projection transforms a source to a destination beyond flattening the object model. Without extra configuration, AutoMapper requires a flattened destination to match the source type's naming structure.  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.
  • 15. Projection  For example, we might want to turn this source structure:  Into something that works better for an input form on a web page:
  • 16. Projection 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:
  • 17. Projection  ForMember() and MapFrom() in AutoMapper Two important functions in AutoMapper play an important role in object mapping.  Suppose our model/viewmodel class has a property FullName, and from the DTO we want to add the First Name and Last Name of the user to make it a full name and bind it to the model. For these kinds of scenarios ForMember() andMapFrom() come in handy.  Here we are saying that ForMember FullName in our model class maps properties from FirstName andLastName of User DTO.

Hinweis der Redaktion

  1. We see here that there are eight properties that are similar to each other but each set lies in a separate class, one in the Model, and one in the Users class. And what we do is one by one we bind these properties to our model and pass it to the View. Now the problem is what if we have 100 column records coming from the database, and also our model has the same number of properties, and the code has to be repeated 6-7 times at different scenarios? Now do we still follow such a strategy of binding each property from the database to the model? Trust me, the code will be 100 pages large, and will be charging five times the effort just to bind the model from the domain entities. To overcome this tedious situation AutoMapper is introduced. It not only reduces the effort, but also limits the execution time that has been taken by such a large number of lines to execute.
  2. We see here that there are eight properties that are similar to each other but each set lies in a separate class, one in the Model, and one in the Users class. And what we do is one by one we bind these properties to our model and pass it to the View. Now the problem is what if we have 100 column records coming from the database, and also our model has the same number of properties, and the code has to be repeated 6-7 times at different scenarios? Now do we still follow such a strategy of binding each property from the database to the model? Trust me, the code will be 100 pages large, and will be charging five times the effort just to bind the model from the domain entities. To overcome this tedious situation AutoMapper is introduced. It not only reduces the effort, but also limits the execution time that has been taken by such a large number of lines to execute.