6

In WCF, how to inherit from a class which is not marked with DataContractAttribute or SerializableAttribute and use that as datacontract ?

Ex: I have a custom class called "EmailAttachment" which I inherited from System.Net.Mail.Attachment:

[DataContract]
public class EmailAttachment : Attachment
{
   [DataMember]
   public string AttachmentURL
   {
       set;
       get;
   }
   [DataMember]
   public string DisplayName
   {
       set;
       get;
   }
}

But when I publish the service, it's throwing a runtime error saying that:

System.Runtime.Serialization.InvalidDataContractException: Type 'EmailAttachment' cannot inherit from a type that is not marked with DataContractAttribute or SerializableAttribute.

What's the workaround for this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Shyju
  • 214,206
  • 104
  • 411
  • 497

1 Answers1

0

It depends what you want your data contract to look like. Can't you use a wrapper rather than a derived class? Something like:

[DataContract]
public class EmailAttachment
{
   public EmailAttachment(){}

   internal EmailAttachment(Attachment inner) {_attachment = inner;}

   [DataMember]
   public string AttachmentURL
   {
       set;
       get;
   }
   [DataMember]
   public string DisplayName
   {
       set;
       get;
   }

   private Attachment  _attachment;
}

If there is any state from the inner System.Mail.Attachment you want to expose in the data contract, you'd then add DataMember properties to surface that.

Chris Dickson
  • 11,964
  • 1
  • 39
  • 60