How to use AutoMapper to map a DataRow to an objec

2019-02-26 03:22发布

问题:

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.

回答1:

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


标签: AutoMapper