【问题标题】:How to correctly use soap webservice client in c#如何在c#中正确使用soap webservice客户端
【发布时间】:2019-01-04 09:57:06
【问题描述】:

我是 C# 新手,尝试使用 SOAP Web 服务,我生成了对 WSDL 的服务引用,并且能够执行以下操作来检索响应的 DataSet。

SportingGatewaySoapClient myServices = new SportingGatewaySoapClient("GatewaySoapID");

RSportResults sportsResults = myServices.SportResults("username","password");
System.Data.DataSet dataSet = sportsResults.dsSportResults;

如果我像往常一样遍历数据集,我就能看到正确的信息:

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            Console.WriteLine(item);
        }
    }
}

但我看不到如何将数据直接解组到生成的类中,以便我可以按名称引用它的属性。例如:

 // some code here to convert response to a Sport object
 sport.getSportName()

自动生成的 Reference.cs 文件有这样的类:

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.7.3056.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="https://endpointurl")]
public partial class RSport : object, System.ComponentModel.INotifyPropertyChanged {

    private string sportName;

我在这里错过了什么步骤?

【问题讨论】:

标签: c# web-services soap


【解决方案1】:

您的 WCF 返回一个 DataSet,其中包含 RSport 对象。

因此产生了为DataTable 创建扩展的想法。此扩展使用Reflection 将每一行转换为给定类型的实例

public static class DataTableExtensions
{
    public static IList<T> ToList<T>(this DataTable table) where T : new()
    {
        IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
        IList<T> result = new List<T>();

        foreach (var row in table.Rows)
        {
            var item = CreateItemFromRow<T>((DataRow)row, properties);
            result.Add(item);
        }

        return result;
    }


    private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
    {
        T item = new T();
        foreach (var property in properties)
        {
            property.SetValue(item, row[property.Name], null);
        }
        return item;
    }
}

接下来,你像这样转换你的数据表

System.Data.DataSet dataSet = sportsResults.dsSportResults;
var rs = dataSet.Tables[0].ToList<RSport>();

这是获取数据的方式

【讨论】:

  • 谢谢!这是一个很好的辅助方法。
  • @Fuzz 很高兴为您提供帮助。:) 一个赞会让我开心
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-16
  • 2011-05-16
  • 2015-08-27
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
  • 1970-01-01
相关资源
最近更新 更多