Manual Mapping and AutoMapper Library

Slides:



Advertisements
Similar presentations
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Advertisements

Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Version Control Systems
Auto Mapping Objects SoftUni Team Database Applications
Working with Fluent API Inheritance Strategies
Static Members and Namespaces
Introduction to Entity framework
Databases basics Course Introduction SoftUni Team Databases basics
Interface Segregation / Dependency Inversion
Services & Dependency Injection
Data Structures Course Overview SoftUni Team Data Structures
Introduction to MVC SoftUni Team Introduction to MVC
Deploying Web Application
PHP MVC Frameworks Course Introduction SoftUni Team Technical Trainers
PHP Fundamentals Course Introduction SoftUni Team Technical Trainers
C# Database Fundamentals with Microsoft SQL Server
Introduction to Entity Framework
ASP.NET Integration Testing
Classes, Properties, Constructors, Objects, Namespaces
Mocking tools for easier unit testing
Parsing JSON JSON.NET, LINQ-to-JSON
State Management Cookies, Sessions SoftUni Team State Management
EF Code First (Advanced)
PHP MVC Frameworks MVC Fundamentals SoftUni Team Technical Trainers
C# Databases Advanced with Microsoft SQL Server
EF Advanced Querying Optimize Performance SoftUni Team Advanced
EF Relations Object Composition
Entity Framework: Code First
Parsing XML XDocument and LINQ
Repeating Code Multiple Times
Entity Framework DB From Code, OOP Introduction
Data Definition and Data Types
Databases advanced Course Introduction SoftUni Team Databases advanced
Install and configure theme
Balancing Binary Search Trees, Rotations
Entity Framework: Relations
Caching Data in ASP.NET MVC
Fast String Manipulation
Array and List Algorithms
The Right Way Control Flow
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
Transactions in Entity Framework
C# Advanced Course Introduction SoftUni Team C# Technical Trainers
Databases Advanced Course Introduction SoftUni Team Databases Advanced
Best Practices and Architecture
Best practices and architecture
WordPress Plugins Popular WP Plugins: Sliders, Forms, Contacts, SEO, Forum, Photo Gallery, e-Commerce WordPress Plugins SoftUni Team Technical Trainers.
Data Definition and Data Types
Multidimensional Arrays, Sets, Dictionaries
Extending functionality using Collections
ASP.NET REST Services SoftUni Team ASP.NET REST Services
Exporting and Importing Data
Making big SPA applications
Functional Programming
C# Advanced Course Introduction SoftUni Team C# Technical Trainers
Exporting and Importing Data
Introduction to TypeScript & Angular
CSS Transitions and Animations
Train the Trainers Course
Iterators and Comparators
Hibernate (JPA) Code First Entity Relations
Spring Data Advanced Querying
Version Control Systems
Polymorphism, Interfaces, Abstract Classes
Lean .NET stack for building modern web apps
CSS Transitions and Animations
Presentation transcript:

Manual Mapping and AutoMapper Library Data Transfer Objects Manual Mapping and AutoMapper Library DTOs SoftUni Team Technical Trainers Software University http://softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Table of Contents DTO Definition Manual Mapping AutoMapper © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

sli.do #Entity Questions © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Data Transfer Objects Definition and Usage

What is a Data Transfer Object? A DTO is an object that carries data between processes Used to aggregate only the needed information in a single call In web applications, between the server and client Doesn't contain any logic – only storage of values public class ProductDTO { public string Name { get; set; } public int StockQty { get; set; } }

DTO Usage Scenarios Remove circular references Hide particular properties that clients are not supposed to view Omit some properties in order to reduce payload size Flatten object graphs that contain nested objects, to make them more convenient for clients Decouple your service layer from your database layer

Manual Mapping Relationship Diagram Product ProductId Name Description Storage StorageId Name Location ProductStock Quantity ProductId StorageId Additional data in mapping table

Aggregate information from mapping table Manual Mapping (2) Get product name and stock quantity in a new DTO object var product = context.Products.FirstOrDefault(); var productDto = new ProductDTO { Name = product.Name, StockQty = product.ProductStocks.Sum(ps => ps.Quantity) }; Aggregate information from mapping table

Automatic Translation of Domain Objects AutoMapper Library Automatic Translation of Domain Objects

What is AutoMapper? Library to eliminate manual mapping code Available as a NuGet Package Official Git Hub Page OR Install-Package AutoMapper

Initialization and Configuration AutoMapper offers a static service for use and configuration Add mappings between objects and DTOs Properties will be mapped by name Source Target Mapper.Initialize(cfg => cfg.CreateMap<Product, ProductDTO>()); var product = context.Products.FirstOrDefault(); ProductDTO dto = Mapper.Map<ProductDTO>(product);

Multiple Mappings You can configure all mapping configurations at once Mapper.Initialize(cfg => { cfg.CreateMap<Product, ProductDTO>(); cfg.CreateMap<Order, OrderDTO>(); cfg.CreateMap<Client, ClientDTO>(); cfg.CreateMap<SupportTicket, TicketDTO>(); });

Custom Member Mapping Map properties that don't match naming convention Flatten complex properties Mapper.Initialize(cfg => cfg.CreateMap<Product, ProductDTO>() .ForMember(dto => dto.StockQty, opt => opt.MapFrom(src => src.ProductStocks.Sum(p => p.Quantity)))); Destination property Source Split property Mapper.Initialize(cfg => cfg.CreateMap<Event, CalendarEventForm>() .ForMember(dto => dest.Date, opt => opt.MapFrom(src => src.Date.Date)) .ForMember(dto => dest.Hour, opt => opt.MapFrom(src => src.Date.Hour)) .ForMember(dto => dest.Minute, opt => opt.MapFrom(src => src.Date.Minute)));

Collection Mapping Standard IEnumerable collections are automatically supported You can project a LINQ query using ProjectTo() Source collection List<ProductDTO> productDTOs = Mapper.Map<Products[], List<ProductDTO>>(products); Source collection type Target collection type context.Products .Where(p => p.Id == 18) .ProjectTo<ProductDTO>().ToList();

Flattening Complex Objects Flattening of related objects is automatically supported AutoMapper understands ClinetName is the Name of a Client public class OrderDTO { public string ClientName { get; set; } public decimal Total { get; set; } } Mapper.Initialize(cfg => cfg.CreateMap<Order, OrderDTO>()); OrderDTO dto = Mapper.Map<Order, OrderDTO>(order);

Inheritance Mapping Inheritance chains are defined via Include() AutoMapper choses the most appropriate child class Register with parent Mapper.Initialize(cfg => { cfg.CreateMap<Order, OrderDto>() .Include<OnlineOrder, OnlineOrderDto>() .Include<MailOrder, MailOrderDto>(); cfg.CreateMap<OnlineOrder, OnlineOrderDto>(); cfg.CreateMap<MailOrder, MailOrderDto>(); }); Order OnlineOrder MailOrder Child mapping

Summary To reduce round-trip latency and payload size, data is transformed into a DTO AutoMapper is a library that automates this process and reduces boilerplate code © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Data Transfer Objects https://softuni.bg/courses/ © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "Databases" course by Telerik Academy under CC-BY-NC-SA license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University Forums forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.