Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper Mapping IEnumerable to DataReader Issue

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 being very flakky...and unpredictable.

1) Same code with same datareader at times brings value back to the dto result set and at times doesnot. 2) I have an ID value coming from database as 100, 200. When it maps to the DTO that is of type integer this 100 is changed to a large value (like 234343211).

Any ideas on why am I seeing this inconsitency. Should I be using the standard while (reader.Read())? and stop using automapper?

like image 341
bkhanal Avatar asked Mar 11 '10 22:03

bkhanal


1 Answers

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());
    }
}
like image 167
Jeff Barnes Avatar answered Nov 03 '22 17:11

Jeff Barnes