【问题标题】:Entity object fails when converting to JSON实体对象在转换为 JSON 时失败
【发布时间】:2014-05-28 16:05:45
【问题描述】:

我一直在尝试将实体框架模型转换为 JSON 以显示在网页中。 Entity 对象创建得很好,但是在返回时会失败。下面是我的 ASP.NET Web API 项目中的代码。通过设置断点,我可以看到对象集合创建得很好。

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;
    }
  }
}

这是我用来调用 ASP.NET Web API 的 HTML/Javascript 代码

<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>

我使用 Fiddler 查看响应,它返回一个 .NET 错误,上面写着 ...

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

内部异常消息是...

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

Patients 是我模型中的一个相关实体,但我很困惑为什么这会是一个问题,因为我只返回 Client 对象。

【问题讨论】:

标签: json entity-framework-6


【解决方案1】:

我找到了一个可行的解决方案,但我承认我不确定它到底是如何工作的。我在返回对象集合的方法中添加了 context.Configuration.ProxyCreationEnabled = false; 行,并返回了我的所有对象。我从下面的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;
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 2012-10-25
    • 2021-11-04
    • 1970-01-01
    • 2020-08-21
    相关资源
    最近更新 更多