Pattern/Strategy for creating BOs from DTOs

时间秒杀一切 提交于 2020-01-14 14:53:27

问题


I like the approach of having property bag objects (DTOs) which define the interface to 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 copying code is quite laborious to write. If the copying code is unavoidable, then where do you put it? In the BO? In a factory? If it is possible to manually avoid writing the boiler plate code then how?

Thanks in advance.


回答1:


That looks like a job for AutoMapper, or (simpler) just add some interfaces.




回答2:


This needs more error handling, and you may need to modify it accommodate properties where the data types don't match, but this shows the essence of a simple solution.

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);
            }
        }



回答3:


Automapper (or similar tools) might be the way forward here. Another approach may be the factory pattern.

Simplest of all 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..
        };
    }
}


来源:https://stackoverflow.com/questions/3123167/pattern-strategy-for-creating-bos-from-dtos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!