You are returning an object that's controlled by Entity Framework... there's going to be at least two issues here:
- The exact error
The 'ObjectContent1' type failed to serialize...
is caused if the entity class has any IQueryable<T>
/ IEnumerable<T>
/ ICollection<T>
properties that are lazy-loaded projections from EF. The serializer cannot handle these.
- If you get past that, you're also disposing the data context, so if the serializer tries to resolve any other lazy-loaded properties, it will fail.
Before you send an object out the door with WebAPI, you want to strip it down to the barest object with only the properties you know you need. You can either do this with a set of model classes in your web project that map back and forth to your EF classes (see @CrazyDart's answer); or project anonymous objects like so:
return new
{
WantedProperty = entity.SomeProperty
};
(Note you'll need to change the WebAPI return type to object
for this to work.)
In recent projects I've seen the developers take the approach of returning anonymous objects and for methods that take arguments, using a dynamic
argument and handling the JSON decomposition in the controller. For small to medium-ish projects this seems to be very efficient. For more formal / larger projects, a proper framework around it with mapping may make more sense.