将具有子项的实体框架对象序列化为XML文件 [英] Serialize Entity Framework object with children to XML file
问题描述
我使用实体框架使用父/子结果集来查询数据,而且我想将这些数据导出到XML文档。
I'm querying data with parent/child result sets using Entity Framework and I want to export this data to an XML document.
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中包含相关子记录的情况下,这样做很好。我还可以让孩子们序列化吗?
This works well except it only serializes the parent without including the related child records in the XML. How can I get the children to serialize as well?
我也尝试使用POCO生成的代码,孩子集合尝试序列化,除非是ICollections,不能序列化。
I also tried using POCO generated code and the child collections attempt to be serialized except they are ICollections which can't be serialized.
无法序列化System.Collections.Generic.ICollection`1类型的成员DataSnapshots.Agreement.AgreementItems [[DataSnapshots.AgreementItem,DataSnapshots,Version = 1.0.0.0,
Cannot serialize member DataSnapshots.Agreement.AgreementItems of type System.Collections.Generic.ICollection`1[[DataSnapshots.AgreementItem, DataSnapshots, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] because it is an interface.
推荐答案
XML序列化的行为与二进制序列化和数据合同的行为不同使用Entity Framework实体时的序列化。后者将序列化已加载到对象图中的任何相关对象,但XML序列化不会,因此您将需要使用 DataContractSerializer
:
XML serialization behaves differently than binary serialization and data contract serialization when working with Entity Framework entities. The latter will serialize any related objects that have been loaded into the object graph, but XML serialization does not, so you will need to use a 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)$来显式加载相关实体您的查询中的c $ c>(其中
儿童
是相关实体的集合的名称)。
Also, Entity Framework uses lazy loading by default for 1:Many relations, and if the referenced objects haven't already been loaded when you go to serialize, then all you'll get is the keys that refer to them. You have to explicitly load the related entities either by calling agreement.Children.Load()
or by using .Include("Children")
in your query (where "Children"
is the name of the collection of related entities).
这篇关于将具有子项的实体框架对象序列化为XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!