我正在使用Entity Framework查询父/子结果集的数据,我想将此数据导出到XML文档.
var agreement = storeops.Agreements.SingleOrDefault(a => a.AgreementNumber == AgreementTextBox.Text); XmlSerializer serializer = new XmlSerializer(agreement.GetType()); XmlWriter writer = XmlWriter.Create("Agreement.xml"); serializer.Serialize(writer,agreement);
这很有效,除了它只序列化父级而不在XML中包含相关的子记录.我怎样才能让孩子们序列化呢?
我也尝试使用POCO生成的代码,并且子集合尝试序列化,除了它们是无法序列化的ICollections.
无法序列化System.Collections.Generic.ICollection`1 [[DataSnapshots.AgreementItem,DataSnapshots,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]]类型的成员DataSnapshots.Agreement.AgreementItems,因为它是一个接口.
在使用Entity Framework实体时,XML序列化的行为与二进制序列化和数据协定序列化不同.后者将序列化已加载到对象图中的任何相关对象,但XML序列化不会,因此您需要使用DataContractSerializer:
var agreement = storeops.Agreements.SingleOrDefault(a => a.AgreementNumber == AgreementTextBox.Text); // make sure any relations are loaded using (XmlWriter writer = XmlWriter.Create("Agreement.xml")) { DataContractSerializer serializer = new DataContractSerializer(agreement.GetType()); serializer.WriteObject(writer,agreement); }
此外,实体框架默认使用延迟加载1:多个关系,如果在进行序列化时尚未加载引用的对象,那么您将获得的只是引用它们的键.您必须通过调用agreement.Children.Load()或在查询中使用.Include(“Children”)显式加载相关实体(其中“Children”是相关实体集合的名称).