数据库有一个Person表,那么,我们做一个person实体。在webservice里面写一个发布方法,发布一个查询方法,可能查询结果有很多个Person,所以应该返回一个数组,问题在于,数组不定长,所以应该使用ArrayList做一下中转,之后调用toArray()方法变成Person[],即return (Person[])result.toArray(typeof(person)).
代码如下:
Person.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/**//// <summary>
/// Person 的摘要说明
/// </summary>
public class Person
...{
private int _personID;
public int PersonID
...{
get
...{
return this._personID;
}
set
...{
this._personID = value;
}
}
private string _name;
public string Name
...{
get
...{
return this._name;
}
set
...{
this._name = value;
}
}
private string _birthday;
public string Birthday
...{
get
...{
return this._birthday;
}
set
...{
this._birthday = value;
}
}
public Person()
...{
}

public Person(string pname,string pbirthday)
...{
this._name = pname;
this._birthday = pbirthday;
}
public Person(DataRow record)
...{
this._personID = Convert.ToInt16(record["personID"]);
this._name = record["name"].ToString();
this._birthday = record["birthday"].ToString();
}
}
Service.cs
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data.SqlTypes;
using System.Collections;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
...{
public const string ConnString = @"Data Source=.SQLEXPRESS;AttachDbFilename=C:Documents and SettingszhouluMy DocumentsVisual Studio 2005WebSiteswsApp_DataFamily.mdf;Integrated Security=True;User Instance=True";
public Service () ...{
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() ...{
return "Hello World";
}
[WebMethod]
public Person[] FindPerson(string Name)
...{
ArrayList result = new ArrayList();
using(SqlConnection conn = new SqlConnection(ConnString))
using (SqlCommand dataCommand = new SqlCommand("dbo.findbyname", conn))
...{
//dataCommand.Parameters.Add("@name", name);
dataCommand.CommandType = CommandType.StoredProcedure;
dataCommand.Parameters.AddWithValue("@name", Name);
SqlDataAdapter dataAdapter = new SqlDataAdapter(dataCommand);
DataTable data = new DataTable();
dataAdapter.Fill(data);
for (int i = 0; i < data.Rows.Count; i++)
...{
result.Add(new Person(data.Rows[i]));
}
}
return (Person[])result.ToArray(typeof(Person));/**////////////问题所在
}
}

被折叠的 条评论
为什么被折叠?



