Reputation: 995
I'm fairly new to WCF's and would like a bit of clarification. I'm attempting to return a List<T>
from my WCF but I get an error when I try to consume it. Cannot conver T[]
to a type of List<T>
. Sample Below.
Question: Is this because WCF's can be consumed by multiple technologies and converts to an array?
Interface:
[ServiceContract]
public interface I_UI_Service
{
[OperationContract]
List<Site> Get_Sites(string ntid);
}
[DataContract]
[Serializable]
public class Site
{
public Site(int id, string description)
{
this.ID = id;
this.Description = description;
}
[DataMember]
public int ID { get; set; }
[DataMember]
public string Description { get; set; }
}
Code:
public List<Site> Get_Sites(string ntid)
{
List<Site> returnList = new List<Site>();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SPROC_Name";
cmd.Parameters.AddWithValue("@NTID", ntid);
using (SqlConnection conn = new SqlConnection(DB_ConnectionString()))
{
cmd.Connection = conn;
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
returnList.Add(new Site(Convert.ToInt16(reader["SiteID"]), reader["SiteDescription"].ToString()));
}
conn.Close();
}
}
return returnList;
}
Consuption using List: (Error)
List<Site> _Sites;
public List<Site> Sites
{
get
{
if (_Sites == null)
{
UI_Data.I_UI_ServiceClient sc = new UI_Data.I_UI_ServiceClient();
_Sites = sc.Get_Sites("MyInfo");
}
return _Sites;
}
}
Consuption using T[ ]: (Makes it work and why my question)
Site[] _Sites;
public Site[] Sites
{
get
{
if (_Sites == null)
{
UI_Data.I_UI_ServiceClient sc = new UI_Data.I_UI_ServiceClient();
_Sites = sc.Get_Sites("MyInfo");
}
return _Sites;
}
}
Upvotes: 1
Views: 1379
Reputation: 251222
WCF serializes generic lists as arrays, but you can convert them back into generic lists by clicking the advanced button when you add the service reference (you'll see the drop downs are populated with array by default, but you can change them to lists).
When you use this option, the arrays sent across the wire will be converted into generic lists for you to consume. It doesn't change how the information is sent.
Upvotes: 5