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.

1

1 Answer 1

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;
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.