Template / Strategy for creating BO from DTO

I like the approach with object bag objects (DTOs) that define the interface for my server, but I don't like writing code like this:

void ModifyDataSomeWay(WibbleDTO wibbleDTO)
{
    WibbleBOWithMethods wibbleBO = new WibbleBOWithMethods();
    wibbleBO.Val1 = wibbleDTO.Val1;
    wibbleBO.Val2 = wibbleDTO.Val2;
}

This copy code is quite time consuming to write. If copying code is inevitable, then where to put it? In BO? In the factory? If you can manually avoid writing the boiler plate code, then how?

Thanks in advance.

+3
source share
3 answers

It looks like work for AutoMapper , or (easier) just add some interfaces.

+4
source

, , , , .

public void CopyTo(object source, object destination)
        {
            var sourceProperties = source.GetType().GetProperties()
                   .Where(p => p.CanRead);
            var destinationProperties = destination.GetType()
                .GetProperties().Where(p => p.CanWrite);
            foreach (var property in sourceProperties)
            {
                var targets = (from d in destinationProperties
                               where d.Name == property.Name
                               select d).ToList();
                if (targets.Count == 0)
                    continue;
                var activeProperty = targets[0];
                object value = property.GetValue(source, null);
                activeProperty.SetValue(destination, value, null);
            }
        }
+1

Automapper (or similar tools) can be here and here. Another approach might be a factory pattern.

The easiest thing would be something like this:

class WibbleBO
{
    public static WibbleBO FromData(WibbleDTO data)
    {
        return new WibbleBO
        {
            Val1 = data.Val1,
            Val2 = data.Val2,
            Val3 = ... // and so on..
        };
    }
}
+1
source

Source: https://habr.com/ru/post/1751863/


All Articles