Tutorial :How do you send complex objects using WCF? Does it work? Is it good?


Can I have a data contract of this shape??

[DataContract]    public class YearlyStatistic{    [DataMember]  public string Year{get;set;}    [DataMember]  public string StatisticName {get;set;}    [DataMember]  public List<MonthlyStatistic> MonthlyStats {get;set}  };  

I am assuming here that class MonthlyStatistic will also need to be a DataContract. Can you do this in a web service?


To use the same model for web services, mark your class as Serializable use the XmlRoot and XmlElement in the System.Xml.Serialization namespace. Here is a sample using your example:

[Serializable]  [XmlRoot("YearlyStatistic")]  public class YearlyStatistic  {      [XmlElement("Year")]      public string Year { get; set; }        [XmlElement("StatisticName")]      public string StatisticName { get; set; }        [XmlElement("MonthlyStats")]      public List<MonthlyStatistic> MonthlyStats { get; set; }   }  

You will have to do the same thing for your complex object properties of the parent object.


Yep, thats standard WCF serialization right there. Are you trying to say the MonthlyStats collection has a property called WeeklyStats, or that each individual MonthlyStatistic has a WeeklyStat collection? If its the former, that doesnt work in WCF natively. You will have to do some fiddling in order to get it to work. If its the latter, its perfectly fine.


Yes, you can send the data contract you mentioned above back and forth from a WCF service. Like you said, MonthlyStatistic and all its members will have to be defined as data contracts themselves or be built in types (like strings).

You can even send and receive more complex types like when you have a base class but want to send or receive an object of a derived class (you would do that using the KnownType attribute). While receiving (de-serialization), from Javascript, there's a trick using which you have to specify the type for WCF. If you are interested, feel free to ask.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »