Search code examples
wcfdatacontract

Returning subclass of DataContract


I have a DataContract which I use as a return type from a WCF service.

[DataContract]
public NameResult
{
    [DataMember]
    public string Name { get; set; }
}

However, I want to store additional information on the service side, so I create a subclass:

internal ServiceNameResult : NameResult
{
    internal Guid ID { get; set; }
}

However, it seems I am unable to use instances of this as a result value (the error I get on the client isn't very helpful - Unrecognized error 109 (0x6d).

Basically, if I do;

NameResult GetName() 
{
    NameResult result = {...}
    return result;
}

Then it works, but if I do;

NameResult GetName()
{
    ServiceNameResult result = {...}
    return result;
}

It doesn't. I don't really want to have to copy the properties from the ServiceNameResult to a new NameResult. Hopefully there is a way to make this work?

I've already put [IgnoreDataMember] on the subclass, but that makes no difference.

Thanks.


Solution

  • Here is one way to approach this problem. You could use composition to achieve what you're looking for:

    internal class ServiceNameResult
    {
        object OtherInformation { get; set; }
    
        NameResult Result { get; set; }
    }
    

    So your internal service implementation can hold a reference to the client return object as well as additional information, but you don't pollute your interface.