Feedback will be sent to lớn romanhords.com: By pressing the submit button, your feedback will be used khổng lồ improve romanhords.com products and services. Privacy policy.
Bạn đang xem: Data transfer object
In this article
by Mike Wasson
Download Completed Project
Right now, our website API exposes the database entities khổng lồ the client. The client receives data that maps directly to lớn your database tables. However, that"s not always a good idea. Sometimes you want to lớn change the shape of the data that you send khổng lồ client. For example, you might want to:
Remove circular references (see previous section).Hide particular properties that clients are not supposed to view.Omit some properties in order khổng lồ reduce payload size.Flatten object graphs that contain nested objects, to lớn make them more convenient for clients.Decouple your service layer from your database layer.To accomplish this, you can define a data transfer object (DTO). A DTO is an object that defines how the data will be sent over the network. Let"s see how that works with the Book entity. In the Models folder, địa chỉ two DTO classes:
namespace BookService.Models public class BookDto public int Id get; set; public string Title get; set; public string AuthorName get; set; namespace BookService.Models public class BookDetailDto public int Id get; set; public string Title get; set; public int Year get; set; public decimal Price get; set; public string AuthorName get; set; public string Genre get; set; The BookDetailDto class includes all of the properties from the Book model, except that AuthorName is a string that will hold the tác giả name. The BookDto class contains a subset of properties from BookDetailDto.
Next, replace the two GET methods in the BooksController class, with versions that return DTOs. We"ll use the LINQ Select statement to lớn convert from Book entities into DTOs.
// GET api/Bookspublic IQueryable GetBooks() var books = from b in db.Books select new BookDto() Id = b.Id, Title = b.Title, AuthorName = b.Author.Name ; return books;// GET api/Books/5
SELECT
Xem thêm: Công Văn Số 850/Bxd Ngày 11/5/2016, Cã´Ng VäN 850/Bxd
Note
In this tutorial, we"re converting to lớn DTOs manually in code. Another option is to lớn use a library like AutoMapper that handles the conversion automatically.