首页 > 解决方案 > 在 C# 中将一个对象转换为另一个对象

问题描述

我是 C# 的新手,dotnet 核心。我正在从数据库中获取数据,如下所示。这个数据很平。我需要转换为另一个对象。

public class Lead
    {
        public long Id { get; set; }

        public short LeadCreatorId { get; set; }

        public short LeadOwnerId { get; set; }

        public string ProductId { get; set; }

        public LeadPriority Priority { get; set; }

        public LeadStatus Status { get; set; }

        public long LeadCustomerId { get; set; }  

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string EmailAddress { get; set; }

        public string MobileNo { get; set; }

        public DateTime CreatedOn { get; set; }
    }

我需要将其转换为下面的对象。

public class LeadDto
    {
        public long Id { get; set; }

        public short LeadCreatorId { get; set; }

        public short LeadOwnerId { get; set; }

        public string ProductId { get; set; }

        public LeadPriority Priority { get; set; }

        public LeadStatus Status { get; set; }

        public LeadCustomer LeadCustomer { get; set; }

        public DateTime CreatedOn { get; set; }
    }

LeadCustomer 如下所示 -

public class LeadCustomer{

            public long Id { get; set; }

            public string FirstName { get; set; }

            public string LastName { get; set; }

            public string EmailAddress { get; set; }

            public string MobileNo { get; set; }
}

我怎样才能轻松做到这一点?我可以使用 dto 进行转换吗?

标签: c#.net-core

解决方案


由于LeadDtoLeadCustomer取决于Lead

一种选择是添加一个构造函数,并将LeadDto对象作为参数并映射到属性。LeadCustomerLead

另一种选择是创建一个静态扩展方法。

public static LeadDto ToLeadDto(this Lead lead)
{
   return new LeadDto(){
      this.Id = lead.Id;
      // Etc..
   }
}

然后你可以使用喜欢

LeadDto myObj = someLead.ToLeadDto();

另一种选择是使用 AutoMapper 之类的库。IMO,我从未使用过它,并且对于您所说的需求来说太过分了。


推荐阅读