Convert DataRow to Object with AutoMapper

前端 未结 1 401
悲哀的现实
悲哀的现实 2020-12-11 06:15

I can successfully map from IDataReader to a List of objects but when I want to take one DataRow it doesn\'t seem to work as expected.

Am I missing something simple

相关标签:
1条回答
  • 2020-12-11 06:22

    You will have to implement your own custom value resolver

    https://github.com/AutoMapper/AutoMapper/wiki/Custom-value-resolvers

    UPDATE

    public class CustomResolver : IValueResolver
    {
        public ResolutionResult Resolve(ResolutionResult source)
        {
            return source.New( Convert.ChangeType((source.Context.SourceValue as DataRow)[source.Context.MemberName], source.Context.DestinationType));
        }
    }
    

    and here is how to use it

    Mapper.CreateMap<DataRow,myObject>().ForAllMembers(m=>m.ResolveUsing<CustomResolver>());
    var dest = Mapper.Map<myObject>(row);
    

    I recommend using Dapper. That way your data coming from database will be strongly typed or dynamic, and Automapper should be able to figure out the mappings.

    CSV files can be read by Dapper through ODBC, I believe. But for CSV I'd recommend the LinqToCSV Nuget package instead.

    0 讨论(0)
提交回复
热议问题