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/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="https://romanhords.com/cong-van-so-850-bxd-ngay-11-5-2016/" 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="https://romanhords.com/tags/dto">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="https://romanhords.com/trong-luong-tinh/">Trọng lượng tịnh</a></li><li class="mb-3"><a href="https://romanhords.com/nam-sinh-nam-1976-mang-gi/">Sinh năm 1976 mệnh gì, tuổi gì và hợp màu gì?</a></li><li class="mb-3"><a href="https://romanhords.com/tu-vi-1994-nam-2021/">Tử vi 1994 năm 2021</a></li><li class="mb-3"><a href="https://romanhords.com/dieu-che-do-rong-xung/">Điều chế độ rộng xung</a></li><li class="mb-3"><a href="https://romanhords.com/loi-win-7/">Lỗi win 7</a></li><li class="mb-3"><a href="https://romanhords.com/press-kit-la-gi/">Press kit là gì</a></li><li class="mb-3"><a href="https://romanhords.com/nguyen-la-gi/">Nguyên là gì</a></li><li class="mb-3"><a href="https://romanhords.com/spectrum-la-gi/">Spectrum la gì</a></li><li class="mb-3"><a href="https://romanhords.com/trai-nghiem-tieng-anh-la-gi/">Trải nghiệm tiếng anh là gì</a></li><li class="mb-3"><a href="https://romanhords.com/data-execution-prevention-la-gi/">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: "https://romanhords.com/admin/post_all.php?grab", type: "POST", data: {id: id}, success: function(data){ data = $.parseJSON(data); if(data.type==='success') { location.href='https://romanhords.com/dto/'; } else { $this.html('<b>Lỗi</b>'); } } }); }); </script> <p><span style="color: #ffffff;"><a style="color: #ffffff;" href="https://meeyland.com/tag/lich-thi-dau-world-cup-2022/">Lịch thi đấu World Cup</a></span></p> <!----------footer--------------> <div id="footer"> <a href="https://romanhords.com">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 © 2023 <a href="https://romanhords.com">romanhords.com</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>