2015-11-19 58 views
1

我已經編寫了一個非常簡單的Web服務,它可以從我的SQL DB中的表中選擇最上面的一個結果。我在我的Web服務中調用該類時出現問題。我的Web服務中有3個變量在我的類中。我只想將變量分配給我使用Web服務的項目中的一組變量。從Web服務中的select語句獲取結果

我在我的Web服務中插入了我的數據庫中的另一個類,它工作正常,所以我知道該Web服務正在工作。

這是我有:

Web服務

[OperationContract] 
void ViewDetails(); 

[DataContract] 
public class ViewDetails 
{ 
    string titleView = string.Empty; 
    string descriptionView = string.Empty; 
    string authorView = string.Empty; 

    [DataMember] 
    public string TitleView 
    { 
     get { return titleView ; } 
     set { titleView = value; } 
    } 

    [DataMember] 
    public string DescriptionView 
    { 
     get { return descriptionView ; } 
     set { descriptionView = value; } 
    } 

    [DataMember] 
    public string AuthorView 
    { 
     get { return authorView ; } 
     set { authorView = value; } 
    } 
} 

public ViewDetails ViewDetails() 
    { 
     string titleView; 
     string descriptionView; 
     string authorView; 
     SqlConnection conn = new SqlConnection(strConnString); 
     conn.Open(); 
     SqlCommand cmd = new SqlCommand("SELECT TOP 1 [My_Title] AS 'Title', [My_Description] AS 'Description', [My_Author] AS 'Author' FROM [TBL_My_Table]", conn); 

     SqlDataReader rdrDetails = cmd.ExecuteReader(); 

     if (rdrDetails.HasRows) 
     { 
      titleView = rdrDetails.GetSqlString(rdrDetails.GetOrdinal("Title")).ToString(); 
      sescriptionView = rdrDetails.GetSqlString(rdrDetails.GetOrdinal("Description")).ToString(); 
      authorView = rdrDetails.GetSqlString(rdrDetails.GetOrdinal("Author")).ToString(); 
     }   
     conn.Close(); 

     return new ViewDetails 
     { 
      TitleView = titleView, 
      DescriptionView = descriptionView, 
      AuthorView = authorView 
     }; 
    } 

當我想填補變量與查詢結果

public Page1() 
{ 
    this.InitializeComponent(); 
} 

誰能幫我搶3個變量我正在填寫Web服務並將它們帶到上面的類中進行顯示唉在我的屏幕上?

的什麼,我試圖完成

private void btnView_Click(object sender, RoutedEventArgs e) 
    { 
     ServiceReference1.Service1Client client = new ServiceReference1.Service1Client(); 
     string author = string.Empty; 

     //this is what I think I should be able to do 
     author = client.ViewDetailsAsync.TitleView; 

    } 

回答

1

您的Web服務實例實際上不是返回什麼。它抓取數據,將數據存儲在三個局部變量中,然後結束。永遠不要使用ViewDetails類或向調用者提供這些值。

更改Web服務方法返回一個ViewDetails

public ViewDetails ViewDetails() 
{ 
    // your code 
} 

然後從方法返回一個對象的實例:

public ViewDetails ViewDetails() 
{ 
    // your code 

    return new ViewDetails 
    { 
     TitleView = titleView, 
     DescriptionView = descriptionView, 
     AuthorView = authorView 
    }; 
} 

然後任何時間的東西調用Web服務方法,將接收該方法獲取的值。

+0

我已經更新了我的答案和你一起編輯。它給我錯誤「使用未分配的變量titleView」。我知道這意味着什麼,但我將這個變量賦值爲一個值....它正在爲所有3變量做回報 – Code

+0

@Code:良好的捕獲。該代碼僅分配給「if」塊中的那些變量。如果沒有滿足這個條件,它們就沒有分配。只需用默認值初始化它們即可。例如:'string titleView = string.Empty;'等等。 – David

+0

完美,現在讓我試試看看我現在是否可以在我的其他項目中調用它..現在真正的樂趣開始了!支持 – Code