views:

1330

answers:

3

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?

+1  A: 

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.

Mike_G
+2  A: 

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.

Michael Kniskern
+1  A: 

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.

floatingfrisbee
please do tell :)
Perpetualcoder
If you are using JavaScript without using any kind of clientside stubs, and hitting a WCF service that could be taking in or giving out base types or interfaces, you need to specify the type of the object being supplied. You can do this by using the __type variable in your JavaScript argument object. There's a lot to write here so I wrote an article on my blog. Feel free to check it out. http://coab.wordpress.com/2010/03/01/serializing-and-deserializing-derived-types-or-interfaces-in-wcf/
floatingfrisbee