AutoMapper Mapping IEnumerable to DataReader Issue

后端 未结 1 906
鱼传尺愫
鱼传尺愫 2020-12-28 23:57

I am using AutoMapper to datareader using code as discussed below http://elegantcode.com/2009/10/16/mapping-from-idatareaderidatarecord-with-automapper/

I see it bei

相关标签:
1条回答
  • 2020-12-29 00:24

    I ran into this same problem. It seems to occur when your source type and destination type are not exactly the same.

    In my case, I had a SQL Server table with an ID field that was of type INT. The value was being mapped to a class with a property that was of type long (Int64). This would result in the expected value of 100 getting mapped to something like 668386727769314912. After changing the table schema so that ID is a BIGINT, the values always mapped correctly.

    I would recommend looking closely at the source type and destination type to ensure they are exactly the same. Apparently, conversions that you would expect to work implicitly (like Int32 to Int64) can cause problems.

    Here is an example that will reproduce the problem:

    public class DataMapperIssue
    {
        public class Person
        {
            public long id { get; set; }
            public string first_name { get; set; }
            public string last_name { get; set; }
        }
    
        public static void run()
        {
            var table = new DataTable();
    
            table.Columns.Add("id", typeof(int));
            table.Columns.Add("first_name", typeof(string));
            table.Columns.Add("last_name", typeof(string));
    
            table.Rows.Add(100, "Jeff", "Barnes");
            table.Rows.Add(101, "George", "Costanza");
            table.Rows.Add(102, "Stewie", "Griffin");
            table.Rows.Add(103, "Stan", "Marsh");
            table.Rows.Add(104, "Eric", "Cartman");
    
            AutoMapper.Mapper.Reset();
            AutoMapper.Mapper.CreateMap<IDataReader, Person>();
    
            var results = AutoMapper.Mapper.Map<IDataReader, IList<Person>>(table.CreateDataReader());
        }
    }
    
    0 讨论(0)
提交回复
热议问题