Search code examples
jsonwcfrestservicedatacontract

DataContract and Serializable in WCF Service


I try to write a demo with WCF (REST) Service, and I use LinqToSQL as my db operator. When I try to pub [DataContract] or [Serializable] on top of my domain object, it cannot be serialized to JSON. I only can get a pair of '{}' in my browser. After removing [DataContract] or [Serializable] attribute, it become normal again.

[DataContract]
public partial class MyDoc{ } // a Linq To SQL domain class

get method:

    [WebGet(UriTemplate = "GetMyDoc/{docID}",ResponseFormat=WebMessageFormat.Json)]       
    [ServiceKnownType(typeof(MyDoc))]
    public WcfRESTfulTest.Db.MyDoc GetMyDoc(string docID)
    {
        WcfRESTfulTest.Db.DbDataContext db = new DbDataContext();
        var query = db.MyDocs.Where(d => d.DocID.Equals(Int32.Parse(docID)));
        return query.FirstOrDefault();
    }

Solution

  • If you don't use the [DataContract] attribute, all public properties will be serialized. If you do use it, you'll have to opt-in the properties you want to serialize, using the [DataMember] attribute.