JMorgan
JMorgan

Reputation: 805

XML Serialization of Entity Objects

I am trying to serialize and EF 4.0 object graph to XML to pass via a WCF service. In the past I have done this with DTO's/POCO's (usually for JSON serialization). In this case since I am only doing XML serialization it seemed that I should just be able to serialize the entity objects directly however, I am running into this conundrum:

  1. If I do not detach the entity, serialization throws an error that the object context has been disposed (because it has at that point so this is expected).

  2. If I detach the entity, any related objects loaded in the navigation properties are dropped.

My expectation was that if I enumerated any linked entities, then detached the object from the context I would still have that relationship available for serialization.

So my question, is there anyway to directly serialize an entity object and retain any loaded navigation properties/collections?

Thanks...

Upvotes: 3

Views: 3460

Answers (1)

Nekresh
Nekresh

Reputation: 2988

When serializing an object, the serializer will walk the entire object graph.

  • If your object is attached, it will force-load every lazy-load navigations. Thus, if your context is disposed, you'll get an exception.
  • According to msdn, when an item in a navigation property is detached, it doesn't appear anymore in the navigation property. I think it is the same when detaching an object and accessing it's navigation property.

I think you should make DTO/POCO's from you entity object before serializing. However, you should have a look at automapper which will help you converting your object from entity to DTO and back.

Upvotes: 1

Related Questions