0

I have been trying to get an Entity Framework model to convert to JSON to display in a web page. The Entity object is created fine but something fails when it is returned. Below is the code from my ASP.NET Web API project. By setting a breakpoint I can see the object collection is created just fine.

public class ClientsController : ApiController
{
  public IEnumerable<Client> GetAllClients()
  {
    using (var context = new MyClientModel.MyEntities())
    {
      var query = context.Clients.Where(c => c.State == "CA");
      var customers = query.ToList();
      return customers;
    }
  }
}

Here is the HTML/Javascript code I use to call the ASP.NET Web API

<script>
  var uri = 'api/clients';

  $(document).ready(function () {
    // Send an AJAX request
    $.getJSON(uri)
        .done(function (data) {
          // On success, 'data' contains a list of products.
          alert('Made it!'); // ** Never reaches here **
          $.each(data, function (key, item) {
            // Add a list item for the product.
            $('<li>', { text: item }).appendTo($('#clients'));
          });
        });
  });
</script>

I use Fiddler to view the response and it returns a .NET error that says ...

The 'ObjectContent' type failed to serialize the response body for content type 'application/json; charset=utf-8'."

and the inner exception message is ...

Error getting value from 'Patients' on 'System.Data.Entity.DynamicProxies.Client

Patients is a related entity in my model but I am confused why it would be an issue as I am only returning Client objects.

webworm
  • 10,587
  • 33
  • 120
  • 217
  • See previous question: http://stackoverflow.com/questions/657939/serialize-entity-framework-objects-into-json – Paige Cook May 28 '14 at 17:36

1 Answers1

1

I found a solution that works, though I admit I am not sure exactly how it works. I added the line context.Configuration.ProxyCreationEnabled = false; to my method that returns the object collection and all my objects were returned. I got the code from the following SO Question - WebApi with EF Code First generates error when having parent child relation.

public class ClientsController : ApiController
{
  public IEnumerable<Client> GetAllClients()
  {
    using (var context = new MyClientModel.MyEntities())
    {
      context.Configuration.ProxyCreationEnabled = false; // ** New code here **
      var query = context.Clients.Where(c => c.State == "CA");
      var customers = query.ToList();
      return customers;
    }
  }
}
Community
  • 1
  • 1
webworm
  • 10,587
  • 33
  • 120
  • 217