If I have a Customer
class that just has simple properties (e.g. Name
, etc.) then I can create a CustomersController
that derives from
OK, apologies for answering my own question, especially after all the help I've received (thanks tugberk), but there was a simple(r) solution.
As tugberk pointed out, the problem was that I was using Entity Framework code-first to work with my POCO objects. When the framework attempted to serialize my objects, it was serializing the EF proxy classes rather than just the POCO objects.
Tugberk suggested using DTO to pass and receive the data (essentially creating new classes for this purpose), but I really didn't want to do that, since my POCO classes looked perfectly adequate to me, and having duplicate classes does not seem very DRY.
I then discovered (via https://stackoverflow.com/a/11386206/98422) that I could turn off proxy generation on the DbContext in my controller (as below), and this would cause the POCO objects to be serialized rather than the proxy classes - and thus avoid the 500 error:
db.Configuration.ProxyCreationEnabled = false;
That was only 50% of the solution, though, because although this avoided the error, it did not include any data for the child objects. (Those came through in the XML as nil). That's because my POCO classes are set up for lazy loading via EF. To get around that, I had to explicitly load the child objects:
return db.Customers.Include("Orders").AsEnumerable();
Job done, and thankfully not much code to write.
You are passing an Entity Framework entity which will cause problems. You need Data Transfer Objects to pass and receive your data. Because you bind entities together, it won't allow you to serialize the data.