您可以使用自动映射器对所有未映射的属性执行特定操作吗?
Can you do a specific action with all non mapped properties using automapper?
我正在实施一项导入功能,该功能将读取电子表格文件并将所有行保存为 DB
上的记录。
我已经有了将电子表格转换为 DataSet
.
的代码
我现在遇到的问题是 class 我需要将 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
而不是普通的 class 映射,但可以做到。在 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;
}
我正在实施一项导入功能,该功能将读取电子表格文件并将所有行保存为 DB
上的记录。
我已经有了将电子表格转换为 DataSet
.
我现在遇到的问题是 class 我需要将 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
而不是普通的 class 映射,但可以做到。在 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;
}