How to use AutoMapper to map a DataRow to an object in a WCF service?

狂风中的少年 提交于 2019-12-02 04:54:01

问题


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


来源:https://stackoverflow.com/questions/16222313/how-to-use-automapper-to-map-a-datarow-to-an-object-in-a-wcf-service

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!