简体   繁体   English

如果我们在API中不使用DTO,会发生什么?

[英]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. 例如:“学生”是域模型,我直接在我的API Action方法中使用“学生”对象。

        // 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. 大多数情况下,DTO较轻,从而导致传输的数据较少。
  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. 您必须序列化域对象或使用DTO展平对象。

  1. Your API will evolve with your domain model if you don't use DTO's. 如果您不使用DTO,API会随您的域模型一起发展。 This might break your external consumers apps when your API is public. 当您的API公开时,这可能会破坏您的外部使用者应用。

It is fine, for DTO is what it means, Data Transfer Object. 很好,因为DTO就是数据传输对象。 Unless your views have a different need, then using a model based on a DTO is fine. 除非您的视图有不同的需求,否则使用基于DTO的模型就可以了。

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. 我的意思是,如果您要开发真正的长期解决方案,则必须使用DTO并使代码更结构化。 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. 如果使用DTO ,则可以创建更多特定的实体。 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可以帮助您的示例。

DTO (Data Transfer objects) is a data container for moving data between layers. DTO(数据传输对象)是用于在层之间移动数据的数据容器。 They are also termed as transfer objects. 它们也称为传输对象。 DTO is only used to pass data and does not contain any business logic. DTO仅用于传递数据,不包含任何业务逻辑。 They only have simple setters and getters. 他们只有简单的setter和getter。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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