Feedback will be sent to lớn By pressing the submit button, your feedback will be used khổng lồ improve 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/5public async Task GetBook(int id) var book = await db.Books.Include(b => b.Author).Select(b => new BookDetailDto() Id = b.Id, Title = b.Title, Year = b.Year, Price = b.Price, AuthorName = b.Author.Name, Genre = b.Genre ).SingleOrDefaultAsync(b => b.Id == id); if (book == null) return NotFound(); return Ok(book);Here is the SQL generated by the new GetBooks method. You can see that EF translates the LINQ Select into a SQL SELECT statement.

SELECT . AS , . AS <Title>, <Extent2>.<Name> AS <Name> FROM <dbo>.<Books> AS <Extent1> INNER JOIN <dbo>.<Authors> AS <Extent2> ON <Extent1>.<AuthorId> = <Extent2>.<Id>Finally, modify the PostBook method lớn return a DTO.<br><br>Xem thêm: <a href="" title="Công Văn Số 850/Bxd Ngày 11/5/2016, Cã´Ng VäƒN 850/Bxd">Công Văn Số 850/Bxd Ngày 11/5/2016, Cã´Ng VäƒN 850/Bxd</a><br><br></p><p><ResponseType(typeof(BookDto))>public async Task PostBook(Book book) if (!ModelState.IsValid) return BadRequest(ModelState); db.Books.Add(book); await db.SaveChangesAsync(); // New code: // Load author name db.Entry(book).Reference(x => x.Author).Load(); var dto = new BookDto() Id = book.Id, Title = book.Title, AuthorName = book.Author.Name ; return CreatedAtRoute("DefaultApi", new id = book.Id , dto);<br>Note</p><p>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.</p> <!-- <div class="tags"><a href="">dto</a> </div> --> </div> <!--/post-content--> </div> </div> </div> </div> <!----> <div class="col-md-9 offset-md-1"> <aside class="sidebar"> <div class="card mb-3"> <h6 class="card-header"><span>Bài viết liên quan</span></h6> <div class="card-body"> <ul class="list-unstyled"> <li class="mb-3"><a href="">Trọng lượng tịnh</a></li><li class="mb-3"><a href="">Sinh năm 1976 mệnh gì, tuổi gì và hợp màu gì?</a></li><li class="mb-3"><a href="">Tử vi 1994 năm 2021</a></li><li class="mb-3"><a href="">Điều chế độ rộng xung</a></li><li class="mb-3"><a href="">Lỗi win 7</a></li><li class="mb-3"><a href="">Press kit là gì</a></li><li class="mb-3"><a href="">Nguyên là gì</a></li><li class="mb-3"><a href="">Spectrum la gì</a></li><li class="mb-3"><a href="">Trải nghiệm tiếng anh là gì</a></li><li class="mb-3"><a href="">Data execution prevention là gì</a></li> </ul> </div> </div> </aside> </div> <!----> </div> </section> <style> .tags a { color: #fff; background: #909295; padding: 3px 10px; border-radius: 10px; font-size: 13px; line-height: 30px; white-space: nowrap; } .tags a:hover { background: #818182; } </style> <script type="text/javascript"> //hàm add data $(document).on('click', '.crawl', function(e){ e.preventDefault(); $this = $(this); var id = $this.attr('id-bv'); $this.html('<span class="spinner-border spinner-border-sm mr-2"></span>'); //send $.ajax({ url: "", type: "POST", data: {id: id}, success: function(data){ data = $.parseJSON(data); if(data.type==='success') { location.href=''; } else { $this.html('<b>Lỗi</b>'); } } }); }); </script> <!----------footer--------------> <div id="footer"> <a href="">Trang chủ</a> <a href="/lien-he/">Liên Hệ</a> <a href="/gioi-thieu/">Giới Thiệu</a> <a href="/noi-quy/">Nội Quy</a> <a href="/bao-mat/">Bảo Mật</a> <span>Copyright © 2022 <a href=""></a></span> </div> <style> #footer {font-size: 14px;background: #ffffff;padding: 10px;text-align: center;} #footer a {color: #2c2b2b;margin-right: 10px;} </style> <!----------/footer--------------> </main> <script type="text/javascript" src="/js/lazy-img.js"></script> </body></html>