简体   繁体   中英

What happens if we don't use DTOs in our API?

For Example: "Student" is Domain Model and i am using the "student" object directly in my API Action method.

        // Domain Model.
        pubic class Student
        {
            public int Id { get; set; }
            public string FirstName{ get; set; }
            public string LastName { get; set; }
            public string Gender{ get; set; }
            public DateTime? BirthDate { get; set; }
        }

       //Simple API method that Add new student details to the database.
       [HttpPost]
       public IHttpActionResult GetStudents(Student student)
       {
           if (!ModelState.IsValid)
               return BadRequest();

              _context_.student.Add(student);
              _context_.SaveChanges();
              return Created(new Uri(Request.RequestUri + "/"), student.Id);
       }
  1. You have a chance to expose your domain model to untrusted clients.
  2. Most of the times DTO's are lighter which result in less data transferred.
  3. Sometimes domain model have complex types included.

     public class Student { //... public ICollection<Course> Courses { get; set; } } public class Course { public int Id { get; set; } //... } 

This might not satisfy the client. You have to either serialize domain object or use DTO to flatten the object.

  1. Your API will evolve with your domain model if you don't use DTO's. This might break your external consumers apps when your API is public.

It is fine, for DTO is what it means, Data Transfer Object. Unless your views have a different need, then using a model based on a DTO is fine.

It really will save you time in future. I mean if you are developing really long term solution you must use DTO and make you code more structured. You must have different layers. Like data layer, presentation layer, business layer etc. And all this layers are supposed to be independent. If you use DTO you are able to create more specific entities. Without mixing up your business logic.

And I've also seen this article . Probably it gets you some examples where DTO can help you.

DTO (Data Transfer objects) is a data container for moving data between layers. They are also termed as transfer objects. DTO is only used to pass data and does not contain any business logic. They only have simple setters and getters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM