如何使用AutoMapper将DataRow映射到WCF服务中的对象? [英] How to use AutoMapper to map a DataRow to an object in a WCF service?

查看:104
本文介绍了如何使用AutoMapper将DataRow映射到WCF服务中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WCF服务,该服务调用存储过程并返回一个DataTable.我想先将DataRows转换为自定义对象,然后再发送给使用者,但不知道该怎么做.可以说我从存储过程中检索了一个客户.为了简短起见,这里是通过DataRow的客户:

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());

我可以轻松地找到客户.现在,我创建了一个Customer对象,如下所示:

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

我从程序包管理器控制台加载了AutoMapper.然后,我像这样对我的客户设置了一个公共静态方法:

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

当我单步执行代码时,从Get()返回的客户中的每个属性都为null.我在这里想念什么?我是否必须添加自定义扩展名才能从DataRow进行映射?这是一个似乎相关的线程,但我认为AutoMapper会支持此操作框,特别是因为属性名称与列名称相同.预先感谢.

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.

推荐答案

这有效!

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将DataRow映射到WCF服务中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆