c# - 在 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 进行转换吗?
解决方案
由于LeadDto
并LeadCustomer
取决于Lead
:
一种选择是添加一个构造函数,并将LeadDto
对象作为参数并映射到属性。LeadCustomer
Lead
另一种选择是创建一个静态扩展方法。
public static LeadDto ToLeadDto(this Lead lead)
{
return new LeadDto(){
this.Id = lead.Id;
// Etc..
}
}
然后你可以使用喜欢
LeadDto myObj = someLead.ToLeadDto();
另一种选择是使用 AutoMapper 之类的库。IMO,我从未使用过它,并且对于您所说的需求来说太过分了。
推荐阅读
- python - 使用python获取英语的英语语音表示
- python - LibreOffice 将 .docx 并行转换为 .pdf 效果不佳
- arduino - 如何检测功能键的 KeyCode 事件?
- java - 在android中实现strip时出现异常没有这样的payment_intent
- python - 管理自动化数据处理系统?关于这个主题,我应该研究的研究领域/关键字是否有名称?
- python - 如何从 PIL 模块 python 中修复此错误“fromarray”函数?
- java - 在Java中将布尔数据类型转换为位
- node.js - 尝试为我的 getAll 表行列表构建搜索功能
- c# - 不能在单元测试中使用模拟的接口类
- json - 如何将 json 响应对象的特定数据类型存储在数组中(例如:数字)以将数据源作为变量传递