MVC series Learning (9)-Use of DTO, mvc series learning-dto
The database used for this study is as follows:
That is, the data transmission object, the client communication of the server, automatically defines a small entity class, which only contains the attributes we need to transmit
2. What is the problem if you don't need DTO?
A. When JavaScriptSerializer is used, an error is returned.
Cause: the Teacher entity contains the foreign key entity TeachClass, And the TeachClass contains another set attribute of Teacher, which is then continuously queried and has an endless loop.
When the Teacher object is serialized, the foreign key entity TeachClass will be searched; when the TeachClass object is searched, the Teacher will be re-searched until the loop.
Start solution:
A. Define the DTO class to solve the endless loop.
We can define a new TeachClass class, which does not contain the attributes that will cause an endless loop, that is, the ICollection <Teacher> attribute is not available. Here we also re-declare a class for Teacher.
B. Define partial categories to facilitate additional methods
The endless loop problem is solved in this way. This is DTO, which is simple. Next, serialization may be used in many places. For convenience, we define a method in the class and serialize ourselves. But the problem arises again, because the entity class is generated by EF. Every time we click Save, EF will reinitialize the class according to the tt template and xml configuration information, the method we wrote is written in white. At this time, we thought of a partial classification method that serializes this class in the partial classification.
I have an idea, because EF is looking for a Class Based on the file name, so the class name here cannot be the same as the class file name
C. start using your own DTO class
The Downloaded Program runs normally and no exception is reported.