c# - 在 C# 中将一个对象转换为另一个对象

标签 c# .net-core

我是 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# - 在 C# 中将一个对象转换为另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55349501/

相关文章:

c# - Unity 检查器不将 XML 文档 (<summary>) 显示为工具提示

c# - 有没有办法将环境变量传递给 Visual Studio 项目并在 C# 中使用它?

c# - 将字符串转换为日期时间 [Wed Mar 01, 2017 6 :00 AM] this format in c#

c# - 如何编辑 gpedit 政策

c# - GridView 中的背景颜色

asp.net-core-mvc - 无法生成deps.json以启用迁移

.net-core - 设置 IOCP 线程计数 int .NET Core

c# - 无法从 OrmLiteConfigExtensions (ServiceStack.OrmLite.Core) 加载 System.ComponentModel.Annotations

c# - 在 DotNet 中创建 AWS Cognito PreSignup Lambda

asp.net-core - Microsoft Distributed Redis Cache - 根据模式获取键