2

I have a WCF service that calls a stored procedure and returns a DataTable. I would like to transform the DataRows to custom object before sending to the consumer but can't figure out how to do so. Lets say I retrieved a customer from a stored procedure. To keep things short here is the customer via DataRow:

string lastName = dt.Rows[0]["LastName"].ToString();
string firstName = dt.Rows[0]["FirstName"].ToString();
string age = System.Convert.ToInt32(dt.Rows[0]["Age"].ToString());

I can retrieve the customer easily. Now, I created a Customer object like so:

public Customer
{
     public string LastName {get;set;}
     public string FirstName {get;set;}
     public int Age {get;set;}
}

I loaded AutoMapper from the package manager console. I then put a public static method on my customer like so:

public static Customer Get(DataRow dr)
{
     Mapper.CreateMap<DataRow, Customer>();
     return Mapper.Map<DataRow, Customer>(dr);
}

When I step through my code, every property in the customer returned from Get() is null. What am I missing here? Do I have to add a custom extension to map from a DataRow? Here is a thread that seems related but I thought AutoMapper would support this out of the box especially since the property names are identical to the column names. Thanks in advance.

Community
  • 1
  • 1
BBauer42
  • 3,549
  • 10
  • 44
  • 81

1 Answers1

7

This works!!

public static Customer GetSingle(DataTable dt)
{
    if (dt.Rows.Count > 0) return null;

    List<Customer> c = AutoMapper.Mapper.DynamicMap<IDataReader, List<Customer>>(dt.CreateDataReader());

    return c[0];
}
BBauer42
  • 3,549
  • 10
  • 44
  • 81
  • 2
    For anyone that refers to this after Dec 29, 2014, the Automapper project has removed support for `IDataReader` in Automapper versions 4.0 and higher. Refer to this [commit](https://github.com/AutoMapper/AutoMapper/commit/33831e3b53ed1cd698558daa2db483906ec5c13a). Version 3.1.1 (available on NuGet) still has this functionality. – Cameron Nov 13 '15 at 20:12
  • The `IDataReader` was moved in it's own packet. Automapper.Data – Drag and Drop Nov 17 '21 at 12:20