Auto Mapping Objects SoftUni Team Database Applications 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 What are DTOs and why we need them? How to map them easy?
Questions sli.do #Entity
DTOs
What are they? A DTO is an object that defines how the data will be sent over the network. In some projects you can see it being used as a substitute to the view model, however in a big project they should always be separated.
Why do we need them? 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.
Example Entity DTO public class Book { public int Id { get; set; } [Required] public string Title { get; set; } public int Year { get; set; } public decimal Price { get; set; } public string Genre { get; set; } public int AuthorId { get; set; } public Author Author { get; set; } } public class BookDTO { public int Id { get; set; } public string Title { get; set; } public string AuthorName { get; set; } } Note that the DTO contains an id here, but there are many cases where we will omit it
Mapping done easier
Why not to map manually? It is very boring Can lead to code repetition Adds complexity and more code where it is needed Hard to maintain BookDto dto = new BookDto() { Title = book.Title, AuthorFirstName = book.Author.Name, AuthorId = book.AuthorId };
So? What can I do about it? Download Automapper from NuGet OR PM> Install-Package AutoMapper The automapper is quite elegant and solves the problems we’ve mentioned. Documentation and Source code
Simple mapping: To map the model to it’s corresponding DTO use the following: Now to use the mapper configuration use the following Mapper.Initialize(cfg => cfg.CreateMap<Order, OrderDto>()); //or var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDto>()); var mapper = config.CreateMapper(); // or var mapper = new Mapper(config); OrderDto dto = mapper.Map<OrderDto>(order); OrderDto dto = Mapper.Map<OrderDto>(order);
Mapping specific properties: If you want to map specific properties which do not have an analogue in the original object you can do it using the following: Mapper.Initialize(expression => { expression.CreateMap<Book, BookDto>() .ForMember(bookDto => bookDto.AuthorFirstName, configurationExpression => configurationExpression .MapFrom(book1 => book1.Author.Name)); });
Using projections in LINQ: If you want to map to a DTO while making a LINQuery you can simple make a projections using the .ProjectTo<T> var dtos = context.Books .Where(book1 => book1.Title == "JS for dummies") .OrderBy(book1 => book1.Id) .ProjectTo<BookDto>();
Mapping Inheritance: public class Order { } public class OnlineOrder : Order { } public class OrderDto { } public class OnlineOrderDto : OrderDto { } Mapper.Initialize(cfg => { cfg.CreateMap<Order, OrderDto>() .Include<OnlineOrder, OnlineOrderDto>(); cfg.CreateMap<OnlineOrder, OnlineOrderDto>(); }); // Perform Mapping var order = new OnlineOrder(); var mapped = Mapper.Map(order, order.GetType(), typeof(OrderDto));
Auto mapping 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 @ YouTube youtube.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.