title: Problems serializing DBML objects C#
body: <p>I am trying to serialize some Linq objects using this code.</p>
  
  <pre><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); 
  
      }
  }
  </code></pre>
  
  <p>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.</p>
  
  <blockquote>
    <p>{"Type 'B' with data contract name
    'B:<a href="http://schemas.datacontract.org/2004/07/DLLNAME" rel="nofollow noreferrer">http://schemas.datacontract.org/2004/07/DLLNAME</a>'
    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."}</p>
  </blockquote>
  
  <p>Any ideas? Each goes by itself fine.</p>
  
  <p><strong>Update 1</strong></p>
  
  <p>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,</p>
  
  <pre><code>A item = new B()
  GetSerializedObj(item);
  </code></pre>
  
  <p>That works.</p>
  
  <p>This does not.</p>
  
  <pre><code>C item = new C();
  item.Bs.Add(new B());
  GetSerializedObj(item);
  </code></pre>
  
  <p><strong>Update 2</strong></p>
  
  <p>When you set the serialization to unidirectional, all classes get the datacontract attributes, and you also get datamemeber attributes on the members.</p>