Using AutoMapper with DataTable with missing colum

2019-07-27 02:42发布

问题:

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.

Example:

AutoMapper.Mapper.CreateMap<IDataReader, Person>()
    .FromMember(dest => dest.NumberOfOrders, opt => opt.MapFrom(src => Convert.ToInt32(src["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?

回答1:

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;
    }