2015-11-25 146 views
0

我写了一个相当简单的Web服务,它将SQL查询的结果集放入列表中。我在使用Web服务的项目中调用带有结果集的列表时遇到问题。我将会把我下面的代码:从Web服务获取返回列表

Web服务

[OperationContract] 
List<ViewDetails> ViewDetails(); 

[DataContract] 
public class ViewDetails 
{ 
    public string TitleView { get; set; } 
    public string BodyView { get; set; } 
    public string AuthorView { get; set; } 

    public ViewDetails() { } 
    public ViewDetails(string myTitleView, string myBodyView, string myAuthorView) 
    { 
     this.TitleView = myTitleView; 
     this.BodyView = myBodyView; 
     this.AuthorView = myAuthorView; 
    } 
} 

public List<ViewDetails> ViewDetails() 
    { 
     List<ViewDetails> details = new List<ViewDetails>(); 

     SqlConnection conn = new SqlConnection(strConnString); 
     conn.Open(); 
     SqlCommand cmd = new SqlCommand("SELECT TOP 2 [My_Title] AS 'Title', [My_Body] AS 'Body', [My_Author] AS 'Author' FROM [My_table] ORDER BY [Date] DESC", conn); 
     SqlDataReader rdrDetails = cmd.ExecuteReader(); 

     try 
     { 
      while (rdrDetails.Read()) 
      { 
       details.Add(new ViewDetails(rdrDetails.GetSqlString(rdrDetails.GetOrdinal("Title")).ToString(), rdrDetails.GetSqlString(rdrDetails.GetOrdinal("Body")).ToString(), rdrDetails.GetSqlString(rdrDetails.GetOrdinal("Author")).ToString())); 
      } 
     } 
     catch (Exception e) 
     { 
      //exception 
     } 
     finally 
     { 
      conn.Close(); 
     } 

     return details; 
    } 

项目中,我使用的Web服务

public async void ViewData() 
{ 
     ServiceReference1.Service1Client client = new ServiceReference1.Service1Client(); 
     string title = string.Empty; 
     string body = string.Empty; 
     string author = string.Empty; 

     var res = await client.ViewDetailsAsync(); 
    } 

我希望能够做这样的事情在我ViewData类,所以我可以将结果存储在变量中,并将它们分配给textblocks等。

title = res.TitleView; 

但它不允许我....有人看到我失踪的东西吗?

注意:这是一个普遍的Windows应用程序

+0

你的“catch”没有发现异常。添加'Debug.WriteLine(ex.Message)'给它,看它是否抛出任何异常。它看起来像它。 –

+0

这里是一个基本的一步一步的教程,你可以使用/遵循http://www.codeproject.com/Articles/576820/Basic-Step-by-Step-WCF-WebService – MethodMan

+0

@KosalaW我知道,但我走了通过网络服务,它没有例外。它正确填写清单。但你是对的。 – Code

回答

1

您在ViewDetails数据合同属性中缺少DataMember属性。

[DataContract] 
public class ViewDetails 
{ 
    [DataMember] 
    public string TitleView { get; set; } 
    [DataMember] 
    public string BodyView { get; set; } 
    [DataMember] 
    public string AuthorView { get; set; } 

    public ViewDetails() { } 
    public ViewDetails(string myTitleView, string myBodyView, string myAuthorView) 
    { 
    this.TitleView = myTitleView; 
    this.BodyView = myBodyView; 
    this.AuthorView = myAuthorView; 
    } 
} 
+0

我仍然无法在我的项目中调用该列表的结果....任何想法? – Code

+0

我想我有它,我结合你的解决方案和@ siwydym67 ...将测试和发布结果 – Code

1

你缺少resList<ViewDetails>res不是ViewDetails的实例。因此,您应该输入title = res[0].TitleView;

+0

这不起作用......它不拉动TitleView作为属性 – Code

+0

@Code:同样的问题再次..你检查是否' res'为null? –

+0

@KosalaW不,它不是null。其中的项目已经实例化 – Code