Reputation: 566
I have following DTO objects:
class ParentDTO
{
property1;
property2;
}
class ChildDTO : ParentDTO
{
property3;
}
And normal objects I want to turn to DTO:
class Parent
{
property1;
property2;
}
class Child : Parent
{
property3;
}
(Let's assume I can't directly use Parent and Child classes and I need to use DTOs)
What is correct approach for turning these to DTOs? I'm trying to write method:
object ConvertToDTO<T>(T objectToConvert);
Which will basically turn any object to DTO object according to it's type and then box it to Object. Is this correct approach?
Many thanks!
Upvotes: 0
Views: 1829
Reputation: 2684
For mapping objects I have extensively used something like AutoMapper
or valueinjecter
. There is no harm in creating your own mapping method or class. However, more likely the requirements will grow and you might prefer using something like AutoMapper
. If you want to create your own mapping, better start with a class like :
public class Mapper<DTO>{}
and this class can grow depending what mapping needs you might require.
In terms of how to design and solve problems relating to inheritance, there is no method to madness, you can start with an abstract class or perhaps use interface. As, programming is both Science and Art, use your imagination and skills.
Upvotes: 0
Reputation: 3435
There is a plethora of libraries out there for mapping one object to another object. The amount of boilerplate necessary to implement this "by hand" is tedious to write and error prone.
I would recommend to check out AutoMapper (it features everything necessary for your inheritance case).
Upvotes: 1