将AutoMapper与DataTable一起使用缺少的列 [英] Using AutoMapper with DataTable with missing columns
问题描述
我正在使用AutoMapper将数据表映射到列表.
I'm using AutoMapper to map a datatable to a List.
在我的情况下,数据表的列可能会根据外部变量而变化.
In my scenario, the columns for the datatable may change depending on an outside variable.
我可以成功地将数据表映射到具有以下内容的对象:
I can successfully map the datatable to the object w/ the following:
AutoMapper.Mapper.CreateMap<IDataReader, Person>();
DataTableReader dtr = myDataTable.CreateDataReader();
List<Person> people = new List<Person>();
people = AutoMapper.Mapper.Map<List<Person>>(dtr);
一切正常.但是我需要将某些属性转换为表中可能存在或不存在的列上的整数.
This all works fine. But there are some properties that I need to convert to integer on columns that may or may not exist in the table.
示例:
AutoMapper.Mapper.CreateMap<IDataReader, Person>()
.FromMember(dest => dest.NumberOfOrders, opt => opt.MapFrom(src => Convert.ToInt32(src["HowManyOrders"])));
表中可能并不总是存在"HowManyOrders"列,那么我该如何检查该列是否存在,然后转换该值呢?
The column "HowManyOrders" might not always exist in the table, so how do I go about checking if the column exists and then converting the value if it does?
推荐答案
您应该可以使用AfterMap:
You should be able to use AfterMap:
Mapper.CreateMap<IDataReader, Person>()
.AfterMap((source, dest) =>
{
if (ColumnExists(source, "HowManyOrders"))
{
dest.NumberOfOrders =
Convert.ToInt32(source["HowManyOrders"]);
}
});
...
public bool ColumnExists(IDataReader reader, string columnName)
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader.GetName(i) == columnName)
{
return true;
}
}
return false;
}
这篇关于将AutoMapper与DataTable一起使用缺少的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!