Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

xml serialization - Serialize Entity Framework object with children to XML file

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

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?

I also tried using POCO generated code and the child collections attempt to be serialized except they are ICollections which can't be serialized.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...