Search code examples
linq-to-sqlserialization.net-4.0datacontractserializer

Connected entities not serialized with DataContractSerializer


I am using LINQ-to-SQL and I have the Serialization Mode set to Unidirectional.

I have two entity classes, Country and City, with a one-to-many relationship.

DataContractSerializer serializer = 
  new DataContractSerializer(typeof(IList<Country>), new[] { 
    typeof(EntitySet<City>) // I have also tried with typeof(City)
  });
string xml;
using (Db db = new Db()) {
  IList<Country> countries = db.Countries.ToList();
  // ... some manipulation of the list here, add/remove etc ...
  StringBuilder sb = new StringBuilder();
  using (XmlWriter writer = XmlWriter.Create(sb)) 
    serializer.WriteObject(writer, countries);
  xml = sb.ToString();
}

The resulting XML string has Country entities but no City entities in it.

How do I resolve this?


Solution

  • Calling ToList() seemed to cause the problem.