Search code examples
c#pocodton-tier-architecture

DTO POCO conversion


I have several DTO and corresponding POCOs.

What is the recommended way to convert between them and where to locate the conversion function.

My original idea is to put two conversion functions in POCO and call them ToPOCO , and ToDTO.

But is there any better ideas for this or maybe create a extension methods ?

Thanks, for ideas.


Solution

  • Look at libraries that do this for you:

    My personal lightweight favourite is to use implicit conversion ops. I must add that I use this only when I intend to remove the 'glue' layer after a future refactoring. This may not sit well as a long-term solution in a production environment (because the implicitness makes it easy to miss).

    public class MyPoco
    {
        public static implicit operator MyPoco(MyDTO o)
        {
            if (o == null) return null;
            return new MyPoco {
                SomeAmount = Convert.ToDecimal(o.SomeAmount),
                SomeBool   = Equals("Y", o.SomeBool     ),
                Sub1       = o.Sub1,
                Sub2       = o.Sub2,
            };
        }
        public static implicit operator MyDTO(MyPoco o)
        {
            if (o == null) return null;
            return new MyDTO {
                SomeAmount = o.SomeAmount.ToString(),
                SomeBool   = o.SomeBool     ? "Y":"N",
                Sub1       = o.Sub1,
                Sub2       = o.Sub2,
            };
        }
        public decimal SomeAmount   { get; set; }
        public bool SomeBool        { get; set; }
        public MySubPoco1 Sub1      { get; set; }
        public MySubPoco2 Sub2      { get; set; }
    }