views:

265

answers:

2

I have these classes:

[DataContract]
public class ErrorBase {}

[DataContract]
public class FileMissingError: ErrorBase {}

[DataContract]
public class ResponseFileInquiry
{
  [DataMember]
  public List<ErrorBase> errors {get;set;};
}

An instance of the class ResponseFileInquiry is what my service method returns to the client. Now, if I fill ResponseFileInquiry.errors with instances of ErrorBase, everything works fine, but if I add an instance of inherited type FileMissingError, I get a service side exception during serialization:

Type 'MyNamespace.FileMissingError' with data contract name 'FileMissingError' 
is not expected. Add any types not known statically to the list of known types - 
for example, by using the KnownTypeAttribute attribute or by adding them to the 
list of known types passed to DataContractSerializer.'

So serializer is getting confused because it's expecting the List to contain the declared type objects (ErrorBase) but it's getting inherited type (FileMissingError) objects.

I have the whole bunch of error types and the List will contain combinations of them, so what can I do to make it work???

+3  A: 

Try this:

[DataContract]
[KnownType(typeof(FileMissingError))]
public class ErrorBase {}

As the error message states, any information that cannot be know statically (like the polymorphic relationship you have expressed here) must be supplied via attributes. In this case you need to specify that your FileMissingError data contract is a known type of its base class, ErrorBase.

Andrew Hare
So that means that I need to specify all child Error classes here?Is there any other way of doing that? I don't like the fact that the parent class would be aware of child classes in a way of attached attriibutes and "using" clauses in the class file.The exception said "Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer." So is there any way to just add them to a list of known types? How do I do that?
Andrey
You can pass the list of known types to the serialized only if you are manually serializing the contracts yourself. Since it appears as though you are allowing WCF to handle the serialization for you, the only thing you can do is add a `KnownTypeAttribute` to the base class, one for each child class that it needs to know about.
Andrew Hare
+2  A: 

You should add KnownType attribute to your base class

[DataContract]
[KnownType(typeof(FileMissingError))]
public class ErrorBase {}

Read more about KnownType attribute in this blog

ArsenMkrt
Thanks, the blog entry has all the possible ways of declaring known types.
Andrey