Should the properties in Data Transfer Object expand the foreign keys or simply expose their primary keys
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 enti开发者_Go百科ties, 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.
精彩评论