简体   繁体   English

DTO POCO转换

[英]DTO POCO conversion

I have several DTO and corresponding POCOs. 我有几个DTO和相应的POCO。

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. 我最初的想法是在POCO中放置两个转换函数,并将它们分别称为ToPOCO和ToDTO。

But is there any better ideas for this or maybe create a extension methods ? 但是,对此有更好的主意还是可以创建扩展方法?

Thanks, for ideas. 谢谢你的想法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM