Search code examples
c#.netwcfvisual-studiodatacontract

Can I add a WCF DataContract to a complex type?


I have a complex data type, including a number of functions, as well as the usual get and get methods. My life would be considerably easier if I could use WCF so my client can also use this data type.

Do I

  1. Ignore all the operations, putting [DataMemeber] only where needed.

  2. Put the class in question in a shared library assembly for both client and server to access.

Thanks, Roberto

PS. I realise that the question is probably not as well worded as it could be.


Solution

  • Ok, it turns out to be a combination of all the above answers.

    1. Stick the data classes into a shared assembly, referenced from both the client and server projects.
    2. Make sure you have the "Reuse Types in Referenced Assemblies" item checked in the "Configure Service Reference" dialog.
    3. At the begining of each of your data contracts put a [KnownType] attribute.

    The code looks like so:

    [DataContract]
    [KnownType(typeof(WHS2SmugmugShared.Photo))]
    [KnownType(typeof(WHS2SmugmugShared.PhotoInfo))]
    public class Photo
    {
    //code here
    }
    

    In the above case, I use PhotoInfo in the Photo class. PhotoInfo does NOT have a KnownType attribute associated with it in the class file. And it does not appear to be required.

    This allows you to serialize complex types but still keep their operations.