开发者

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?


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

context.ContextOptions.LazyLoadingEnabled = false;

StackOverflow Source


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜