Search code examples
wcfdata-bindingdatacontract

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?


Solution

  • 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.