Clas
Clas

Reputation: 57

Serialization doesn't accept my KnownTypeAttribute, why?

I've got stuck with a serialization problem. My Silverlight app doesn't expect one of my properties in a businessobject and doesn't know what to do about it. Previously I have solved this by setting a KnownTypeAttribute like the example below but in this case it doesn't work.

I have used to solve it like this:

[DataContract(Name = "baseClass")]
public class baseClass { }

[DataContract(Name = "busObj1")]
public class busObj1 : baseClass { }

[DataContract(Name = "busObj2")]
[KnownType(typeof(busObj1))]
public class busObj2 : baseClass
{
    public busObj1 myObj { get; set; }
}

The only difference know is that I have slightly different structure, like this:

[DataContract(Name = "baseClass")]
public class baseClass { }

[DataContract(Name = "busObj1")]
public class busObj1 : baseClass { }

[DataContract(Name = "busObj2")]
[KnownType(typeof(busObj1))]
public class busObj2 : baseClass
{
    public busObj1 myObj { get; set; }
}

// This is the class that I want to send via WCF and that cannot be serialized
// because the serializer doesn't expect busObj1.
[DataContract(Name = "busObj3")]
public class busObj3 : busObj2 { }

I'm very thankful for any ideas of what could be wrong!

Regards, Clas

Upvotes: 1

Views: 660

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

You need to put the known type attribute on your base object:

[DataContract(Name = "baseClass")]
[KnownType(typeof(busObj1))]
[KnownType(typeof(busObj2))]
[KnownType(typeof(busObj3))]
[KnownType(typeof(busObj4))]
public class baseClass { }

[DataContract(Name = "busObj1")]
public class busObj1 : baseClass { }

[DataContract(Name = "busObj2")]
public class busObj2 : baseClass { }

[DataContract(Name = "busObj3")]
public class busObj3 : busObj1
{
    public busObj2 myObj { get; set; }
}

[DataContract(Name = "busObj4")]
public class busObj4 : busObj3 { }

or if you don't want to pollute your domain models with those attribtues you could also do it in your web.config or use the ServiceKnownType attribute on your Service Contract.

Upvotes: 5

Related Questions