[英]Can you do a specific action with all non mapped properties using automapper?
我正在實現一個導入功能,它將讀取電子表格文件並將所有行保存為DB
記錄。 我已經有代碼將電子表格轉換為DataSet
。
我現在DataRows
的問題是我需要將DataRows
反序列化的類是這樣的:
public class Product
{
public string Name { get; set; }
// More Props
public IDictionary<string, object> Specifications { get; set; }
}
每個DataRow
都將具有所有Product
屬性和一些額外的必須添加到Specifications
Dictionary
。
有沒有辦法配置AutoMapper
將目標中所有不存在的屬性映射到Specifications
Dictionary
的新項目?
您無法執行特定操作,但可以創建自定義映射,查找所有未映射的屬性並將其添加到目標字典。
這有點棘手,因為您是從DataRow
而不是普通類映射,但它可以完成。 在Specifications
的解決方法中,您需要遍歷DataTable
的列,並檢查是否存在具有該名稱的屬性的映射。 如果沒有將它添加到字典中:
private static void ConfigureMappings()
{
Mapper.CreateMap<DataRow, Product>()
.ForMember(p => p.Name, mo => mo.MapFrom(row => row["Name"]))
.ForMember(p => p.ID, mo => mo.MapFrom(row => row["ID"]))
.ForMember(p => p.Specifications, mo => mo.ResolveUsing(MapSpecifications));
}
private static object MapSpecifications(ResolutionResult rr, DataRow row)
{
Dictionary<string, object> specs = new Dictionary<string, object>();
// get all properties mapped in this mapping
var maps = rr.Context.Parent.TypeMap.GetPropertyMaps();
// loop all columns in the table
foreach (DataColumn col in row.Table.Columns)
{
// if no property mapping exists, get value and add to dictionary
if (!maps.Any(map => map.DestinationProperty.Name == col.ColumnName))
{
specs.Add(col.ColumnName, row[col.ColumnName]);
}
}
return specs;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.