Using AutoMapper with DataTable with missing columns

て烟熏妆下的殇ゞ 提交于 2019-12-11 14:48:56

问题


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


来源:https://stackoverflow.com/questions/17434750/using-automapper-with-datatable-with-missing-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!