[英]Automapper map from dataset columns to list of object
I've a dataset with 3 fixed columns and other variables, the dataset is created in C # through a stored procedure.我有一个包含 3 个固定列和其他变量的数据集,该数据集是通过存储过程在 C# 中创建的。
I want to map the dataset with this object via Automapper:我想通过 Automapper 用这个对象映射数据集:
public class PrivacyStatusData
{
public int Id { get; set; }
public string Name{ get; set; }
public string Surname { get; set; }
public List<ConsentData> ConsentList { get; set; }
}
public class ConsentData
{
public string ConsentName { get; set; } // Consent1 Column Name
public bool ConsentValue { get; set; } // Consent1 Value
public DateTime ConsentDate { get; set; } // Consent1Date Value
}
Tanks for the help.坦克的帮助。
I found the solution on my own.我自己找到了解决方案。 Static properties are mapped through the MapFrom function and dynamic properties are mapped through a custom resolver.
静态属性通过 MapFrom 函数映射,动态属性通过自定义解析器映射。 The trick is to map a DataRow instead of a DataTable.
诀窍是映射 DataRow 而不是 DataTable。
The CreateMap definition: CreateMap 定义:
CreateMap<DataRow, PrivacyStatusData>()
.ForMember(dest => dest.Id, orig => orig.MapFrom(row => (int)row["Id"]))
.ForMember(dest => dest.Name, orig => orig.MapFrom(row => row["Name"].ToString()))
.ForMember(dest => dest.Surname, orig => orig.MapFrom(row => row["Surname"].ToString()))
.ForMember(dest => dest.ConsentList, orig => orig.MapFrom<DataRowToConsentDataResolver>());
The resolver:解析器:
public class DataRowToConsentDataResolver : IValueResolver<DataRow, PrivacyStatusData, List<ConsentData>>
{
public List<ConsentData> Resolve(DataRow source, PrivacyStatusData destination, List<ConsentData> destMember, ResolutionContext context)
{
var consentDataList = new List<ConsentData>();
for (int i = 9; i < source.Table.Columns.Count; i += 2)
{
var consentData = new ConsentData();
var consentName = source.Table.Columns[i].ColumnName.Replace("Consenso", "");
consentName = consentName.First().ToString().ToUpper() + consentName.Substring(1).ToLower();
consentData.ConsentName = consentName;
if (source[i].ToString() == "1")
consentData.ConsentValue = true;
consentData.ConsentDate = "-";
var dtDate = new DateTime();
if (DateTime.TryParse(source[i + 1].ToString(), out dtDate))
consentData.ConsentDate = dtDate.ToString("dd MMMM yyyy");
consentDataList.Add(consentData);
}
return consentDataList;
}
}
Tha caller:来电者:
private List<PrivacyStatusData> MapDataTableToPrivacyStatusData(DataTable privacyData)
{
var rows = new List<DataRow>(privacyData.Rows.OfType<DataRow>());
var privacyStatusDataList = mapper.Map<List<DataRow>, List<PrivacyStatusData>>(rows);
return privacyStatusDataList;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.