3

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

2
  • Are you sure that navigation properties are loaded? First problem looks like EF triggers lazy loading get them. Commented Feb 15, 2011 at 23:47
  • I have explicitly accessed the desired navigation property prior to detaching the object. My expectation was that if these values were read (and therefore loaded from the database) that they would still be available after the object was detached. Commented Feb 16, 2011 at 13:29

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.