Should the properties in Data Transfer Object expand the foreign keys or simply expose their primary keys

StackOverflow https://stackoverflow.com/questions/5392093

문제

I have an EmployeeDTO that respresents an Employee record in the database. The Employee table has a relationship to a Department and a 1-to-many relationship to Permission.

In my entities, these are represented as a fully expanded Department property and a List of fully expanded permission objects.

The question is should the DTO have a fully expanded DepartmentDTO property of a DepartmentId? Should the DTO have a list of fully expanded PermissionDTO properties of List of PermissionId?

도움이 되었습니까?

해결책

Just like everything in design, it depends on your needs.

  • If you need to frequently see and bind to child properties and you want to make it as easy as possible for developers to use your DTOs, you may want explicit factory methods to give you fully expanded child properties.
  • If you want simplicity of code, don't expand the foreign key properties and just let developers get the child object/collections they want by key as needed.

You may run into problems in recursion; do you also expand all the foreign-key properties of the Department object too? What if there is a reference to another EmployeeDTO in a subclass of Department?

Microsoft's Entity Framework, as well as other popular business object frameworks, handle this concept by lazy loading -- only fetch the full expanded child property if it is called for by the code. This is probably the most flexible solution, but has a little overhead/lag as child properties can't be fetched in the same database call as the parent object. These are of course not purely DTOs.

다른 팁

Yes and No. It depends on the call and if you would need all extra properties in every call. It can also depends on the ORM technology you use which can implement lazy loading and can affect your decision (if you are passing straight entity objects although it is not recommended).

It is common to create one case DTO containing all necessary properties and one or more DTO object that expose more functionality and are used it other methods. For example, I have a BasicUser class which only contains UserName and DisplayName and I have User which contains more including Permissions and inherits from `BasicUser.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top