Create an XML file from an Entity Framework entity with children.

eager-loading entity entity-framework xml-serialization xmlwriter

Question

Using Entity Framework, I'm querying data using parent/child result sets, 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);

The sole drawback is that the parent record is merely serialized, and the linked child entries are not included in the XML. How can I persuade the kids to serialize too?

I also tried writing code created by POCO, but the child collections couldn't be serialized since they were ICollections.

Because it is an interface, it is not possible to serialize the member DataSnapshots.Agreement.AgreementItems of type System.Collections.Generic.ICollection'1[[DataSnapshots.AgreementItem, DataSnapshots, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].

1
5
6/5/2011 3:55:52 PM

Popular Answer

When dealing with Entity Framework entities, XML serialization operates differently from binary serialization and data contract serialization. Since XML serialization does not serialize related items that have been loaded into the object graph, you must use a different method.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);
}

Additionally, Entity Framework employs lazy loading by default for 1:Many relations; thus, if the referenced objects aren't loaded when you attempt to serialize them, all you'll get is their key references. The linked items must be specifically loaded either by callingagreement.Children.Load() or via use.Include("Children") your question (where"Children" is the title of the group of connected things).

10
6/5/2011 4:33:11 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow