Question:
Is it possible when dealing with dynamic proxy to pull out the underlying POCO when we need to serialize them?
Rationale:
I have a requirement to serialize (XML) my POCO entities using EF Code First but quickly found that DbContext
creates dynamic proxy for my POCO and that makes it hard to serialize.
I have tried the following:
- Disable proxy creation in the
DbContext
and work only with pure POCO. This allows me to serialize the instances any way I like. The only catch is that navigational properties are not being tracked, therefore, I must attach all related entities manually when I want to save otherwise new entities will always be created (see code example). - Implement
ISerializable
interface on the POCO to manually handle serialization. This is a lot of work and is not a sustainable solution.
Code example.
// Attach and update tags
foreach (var tag in entity.Tags)
{
Context.Entry(tag).State = Context.Tags.Any(t => t.ID == tag.ID)
? EntityState.Modified
: EntityState.Added;
}
// Attach and update state.
Context.Entry(entity).State = Context.Resources.Any(x => x.ID == entity.ID)
? EntityState.Modified
: EntityState.Added;
As you can imagine, the complexity can get out of hand when my entity have more relationships.