2

I have the following setup of two classes:

[SerializableAttribute]
public class ParentData{
  [DataMember]
  public string Title{get;set;}
}

[DataContract]
public class ChildData : ParentData{
  [DataMember]
  public string Abstract{get;set;}
}

These two classes are served through a WCF service. However I only want the service to expose the ChildData class to the end user but pull the marked up DataMember properties from the parent. E.g. The consuming client would have a stub class that looked like:

public class ChildData{
  public string Title{get;set;}
  public string Abstract{get;set;}
}

If I uses the parent and child classes as above the stub class only contains the Abstract property.

I have looked at using the KnownType attribute on the ChildData class like so:

[DataContract]
[KnownType(typeOf(ParentData)]
public class ChildData : ParentData{
  [DataMember]
  public string Abstract{get;set;}
}

However this didn't work.

I then applied the DataContract attribute to the ParentData class, however this then creates two stub classes in the client application which I don't want.

Is there any way to tell the serializer that it should flatten the inheritance to that of the sub-class i.e. ChildData

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Michael Edwards
  • 6,308
  • 6
  • 44
  • 75
  • possible duplicate of [Is there any way to hide/flatten base types in WCF service data contracts?](http://stackoverflow.com/questions/3499788/is-there-any-way-to-hide-flatten-base-types-in-wcf-service-data-contracts) – Ladislav Mrnka Jan 05 '11 at 13:15

2 Answers2

1

I believe your ParentData class also needs to have the [DataContract] attribute:

[DataContract]
public class ParentData
{
  [DataMember]
  public string Title{get;set;}
}

The [Serializable] doesn't really help with WCF using the default data contract serializer.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • The problem with adding the [DataContract] attribute on the ParentData class is that the consuming client will create two stub classes that represents the inheritance chain, this is what I want to avoid. To get around this so I can get my project moving is to turn the ParentData class into an interface. This isn't ideal but will work for the time being. – Michael Edwards Jan 07 '11 at 11:44
0

I believe your ParentData class should be marked abstract and also needs to have the [DataContract] attribute:

[DataContract]
public abstract class ParentData
{
  [DataMember]
  public string Title{get;set;}
}

As marc said, the [Serializable] doesn't really help with WCF using the default data contract serializer.

Lucas B
  • 11,793
  • 5
  • 37
  • 50