views:

498

answers:

1

I am trying to serialize some Linq objects using this code.

private byte[] GetSerializedObj(object o)
{
    try
    {
        DataContractSerializer formatter = new DataContractSerializer(o.GetType());
        MemoryStream memStream = new MemoryStream();
        formatter.WriteObject(memStream, o);
        return memStream.ToArray();
    }
    catch (Exception ex)
    {
        throw new Exception("Could not serialize object", ex); 

    }
}

This works get on all objects. I marked the DBML as unidirectional for serialization. I have on my DBML type B which derives from type A. I can serialize each, but type C has a collection of type B on it. When I try to serialize a type C that has its B's loaded, it fails with a message like this.

{"Type 'B' with data contract name 'B:http://schemas.datacontract.org/2004/07/DLLNAME' 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."}

Any ideas? Each goes by itself fine.

Update 1

I should also explain I know what the error means. I have used the knowntype attribute before. I have two issues here. One is that the DBML should generate the known attribute. The other is, why do the classes serialize when I create them themselves. For example,

A item = new B()
GetSerializedObj(item);

That works.

This does not.

C item = new C();
item.Bs.Add(new B());
GetSerializedObj(item);

Update 2

When you set the serialization to unidirectional, all classes get the datacontract attributes, and you also get datamemeber attributes on the members.

+1  A: 

The answer is in the exception message... apply the KnownTypeAttribute to class A :

[KnownType(typeof(B))]
class A
{
    ...
}
Thomas Levesque
Please see update.
Anthony D
I ended up just adding these to the class. I really thought it would get generated.
Anthony D