I have some POCO objects that I'm using in an EF Code First context. So, when I fill them with data, I'm actually dealing with EF proxy objects rather than the POCOs themselves.
I have an ASP.NET MVC4 ApiController that returns my POCO objects, which I'll consume in my client application.
My "GET" method looks something like this:
// GET api/Clients/5
public Client GetClient(int id)
{
Client client = db.Clients.Find(id);
if (client == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return client;
}
That doesn't actually work, because when the serializer tries to serialize the Client object, it's actually dealing with the EF proxy version, which causes it to hiccup. See Can an ApiController return an object with a collection of other objects?
So, I could turn off proxy generation by doing this to my DbContext
:
db.Configuration.ProxyCreationEnabled = false;
Which ensures that I'm dealing with the POCO rather than a proxy. But, now most of the members of my Client class are not populated, since it was the EF proxy that was lazy-loading those for me.
So what I really want is to use the EF proxy class to get the data, and then at the last minute return the original POCO from my method.
How can I do that without manually creating the whole object from scratch (including any nested objects) in code? Surely there must be an easy way - or at least a helper class of some kind?