[英]Can you do a specific action with all non mapped properties using automapper?
I'm implementing an import feature that will read a spreadsheet file and save all rows as records on a DB
. 我正在实现一个导入功能,它将读取电子表格文件并将所有行保存为DB
记录。 I already have code in place that transforms the spreadsheet into a DataSet
. 我已经有代码将电子表格转换为DataSet
。
The problem I have right now is that the class I need to deserialize the DataRows
to is something like this: 我现在DataRows
的问题是我需要将DataRows
反序列化的类是这样的:
public class Product
{
public string Name { get; set; }
// More Props
public IDictionary<string, object> Specifications { get; set; }
}
And each DataRow
will have all the Product
properties and some extra that have to be added into the Specifications
Dictionary
. 每个DataRow
都将具有所有Product
属性和一些额外的必须添加到Specifications
Dictionary
。
Is there a way to configure AutoMapper
to map all non existent properties in the destination into a new item on the Specifications
Dictionary
? 有没有办法配置AutoMapper
将目标中所有不存在的属性映射到Specifications
Dictionary
的新项目?
You can't do a specific action but you can create a custom mapping which finds all unmapped properties and adds them to the destination dictionary. 您无法执行特定操作,但可以创建自定义映射,查找所有未映射的属性并将其添加到目标字典。
This is a little trickier because you are mapping from a DataRow
, rather than a normal class, but it can be done. 这有点棘手,因为您是从DataRow
而不是普通类映射,但它可以完成。 In your resolution method for Specifications
, you need to loop through the columns of the DataTable
and check if there is a mapping for a property with that name. 在Specifications
的解决方法中,您需要遍历DataTable
的列,并检查是否存在具有该名称的属性的映射。 If not add it to the dictionary: 如果没有将它添加到字典中:
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.