[英]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.