【问题标题】:copy contents of dto to another similar dto将 dto 的内容复制到另一个类似的 dto
【发布时间】:2016-09-02 18:43:05
【问题描述】:

我有 2 个非常相似的 dto 对象。我在下面展示了一个示例代码,但我正在使用的实际 2 dto 中有 39 和 40 个属性。 我的问题是,有没有更简单的方法可以将 QuoteDto 的内容复制到 Quote2Dto。

我正在调用一个给我 QuoteDto 对象的遗留项目。我必须调用一个只接受 Quote2Dto 对象的新休息服务项目

如果您需要更多代码,请告诉我。

    public abstract class QuoteDto
    {
        public virtual bool IsWaive { get; set; }
        public virtual bool IsExpired { get; set; }
    }

public abstract class Quote2Dto
    {
        public virtual bool IsWaive { get; set; }
        public virtual bool IsExpired { get; set; }
        public virtual bool IsCancel { get; set; }
    }

【问题讨论】:

    标签: asp.net-mvc c#-4.0 dto


    【解决方案1】:

    通常使用Automapper(或类似库)。它可以复制相同的属性而无需任何预先配置。但是您始终可以配置更高级的属性映射。

    Here you can find Getting Started Guide.

    【讨论】:

      【解决方案2】:

      这里有两个选择。

      您的第一个选项是使用AutoMapper 复制属性。如果您需要更高级的配置,AutoMapper 有一些高级配置。

      第二个选项是在你的 DTO 中创建一个方法,它接受另一个 DTO 并复制属性。(基本上是手动复制属性。)

      看起来像这样:

      class FirstSampleDTO
      {
          public int RandomProperty { get; set; }
          public int RandomProperty2 { get; set; }
          public int RandomProperty3 { get; set; }
      
          private void CopyDTOData(SecondSampleDTO dto)
          {
              dto.RandomProperty = this.RandomProperty;
              dto.RandomProperty2 = this.RandomProperty2;
              dto.RandomProperty3 = this.RandomProperty3;
          }
      }
      
      class SecondSampleDTO
      {
          public int RandomProperty { get; set; }
          public int RandomProperty2 { get; set; }
          public int RandomProperty3 { get; set; }
      
          private void CopyDTOData(FirstSampleDTO dto)
          {
              dto.RandomProperty = this.RandomProperty;
              dto.RandomProperty2 = this.RandomProperty2;
              dto.RandomProperty3 = this.RandomProperty3;
          }
      
      }
      

      (如果您已经拥有 dto 的数据。)

      如果您不打算做那么多映射,我建议使用第二种方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多