Rahma
Rahma

Reputation: 255

Entity framework and DataContractSerializer

I've been reading about serialization of entities graph in an entity framework context using Linq to entities and the different possible serializers: Binary, XmlSerializer and DataContractSerializer. As i understood the binary and XmlSerializer serialize the entity without its relationships. In case relationships are serialized it would cause a problem because of the nature of the resulting xml file structure ( for XmlSerializer). The DataContractSerializer serialize the graph in its whole depth unless the lazy load is disabled.

My question is: I want to serialize a part of the graph. For example if I have an entity A and three related entities B, C and D, only B and D would be serialized with A. I want to use the the DataContractSerializer. If I delete the [DataMemberAttribute] of the unwanted navigational properties would that work?

Upvotes: 3

Views: 1596

Answers (3)

Vivian River
Vivian River

Reputation: 32380

In my experience, it seemed like the only reliable way to disable lazy-loading is to go to the Entity Designer winder, right-click in the background, select "Properties", and set "Lazy Loading Enabled" to false in the Properties window.

Upvotes: 0

Alec
Alec

Reputation: 1706

You can actually disable lazy-loading, serialize/deserialize, and then re-enable lazy-loading.

context.ContextOptions.LazyLoadingEnabled = false;

StackOverflow Source

Upvotes: 1

David Rodrigues
David Rodrigues

Reputation: 622

Since attributes are static metadata you can't mess with them at run-time. And if you remove them from your entity they will be permanently removed.

The Lazy loading isn't probably what you want, since when you load you bring the entire graph, the partial graph cenario only usually comes up on updates or partial inserts.

Your cenario, from what I gathered is when you want to update something, you want to update a partial graph only, and not the entire graph that you have on the client. One way to achieve this is to remove manualy the other DataMembers and set them to null, serialize them, update, and them repair the null references you previously set, finally make sure the ChangeTrackers are all in their previous state.

In our specific development cenario, we achieved this behaviour through a T4 template, that generates all the messy code, generating part of a "DataManager" that handles all the Self Tracking Entities once they exist on the client.

Upvotes: 0

Related Questions