[英]Designing DTOs that contain lists of objects
Suppose I have the following domain models: 假设我有以下领域模型:
Project Task
- Id - Id
- Name - Name
- List<Task> - Project
Projects have many Tasks, and Tasks have one Project. 项目有许多任务,而任务有一个项目。
Now suppose I want to create a TodoListDTO data transfer object. 现在假设我想创建一个TodoListDTO数据传输对象。 My original thought was to just do this:
我最初的想法是这样做:
TodoListDTO
- List<Project>
Seems simple. 看起来很简单。 Then I have access to the List of Tasks within each Project.
然后,我可以访问每个项目中的任务列表。 Then I read in several places that DTOs should be as flat as possible.
然后我在几个地方读到,DTO应该尽可能平整。 But how would I model that without using complex objects?
但是,在不使用复杂对象的情况下如何建模呢?
Instead of TodoListDTO, I could have a ProjectDTO that looks something like: 代替TodoListDTO,我可以拥有一个类似于以下内容的ProjectDTO:
ProjectDTO
- ProjectId
- Name
- List<TaskId>
- List<TaskName>
But having separate lists of TaskIds and TaskNames seems inconvenient, and I don't see how that's any better than just having a List property on the ProjectDTO. 但是,单独列出TaskId和TaskName似乎很不方便,而且我不认为这比在ProjectDTO上具有List属性更好。
What's a good way to handle this? 什么是处理此问题的好方法?
Another thing you could do is create another domain model of 您可以做的另一件事是创建另一个域模型
ProjectTask
- ProjectId
- ProjectName
- TaskId
- TaskName
This could help with the one-to-many relationship (also allowing many-to-many) and side stepping the confusing circluar project->task->Project->task structure. 这可能有助于一对多关系(也允许多对多),并避免使混乱的外接项目->任务->项目->任务结构。 From here you can have your API client group all ProjectTasks by projectId and handle it that way.
在这里,您可以让您的API客户端组通过projectId拥有所有ProjectTasks,并以此方式进行处理。
This being said, I think your original way is fine, but here is an alternative. 话虽这么说,我认为您的原始方式很好,但这是另一种选择。
Your previous classes were simple enough and the standard way of doing it. 您以前的课程非常简单,并且是实现此操作的标准方法。 You would make a Context class that would keep a list of Projects and Tasks.
您将创建一个Context类,该类将保留一个Projects和Tasks列表。 A total of three classes.
共三节课。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.