未使用DataContractSerializer序列化的已连接实体

时间:2011-01-21 15:38:30

标签: linq-to-sql serialization .net-4.0 datacontractserializer

我正在使用LINQ-to-SQL,并且我将Serialization Mode设置为Unidirectional。

我有两个实体类CountryCity,具有一对多的关系。

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();
}

生成的XML字符串包含Country个实体,但其中没有City个实体。

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

调用ToList()似乎会导致问题。