【问题标题】:ASP.NET Web API 2 Child entities missing when serialized序列化时缺少 ASP.NET Web API 2 子实体
【发布时间】:2015-05-11 11:40:40
【问题描述】:

我目前正在构建一个 Angular 网站并使用 Web Api 2 作为我的数据服务。

我在调用 http get 方法时遇到了填充子实体的问题。子实体(字段)不会出现在 Json 响应中。

     //Fetch records by page size
    public ICollection<CompanyStatDomainModel> GetRecordsByPageSize(int page)
    {
        const int pgeSize = 20;

        var result = _companyStatRepo.AllIncluding(c => c.CompanyDomainModel, c => c.RatingDomainModels)
            .OrderBy(c => c.CompanyStatId).Skip(page * pgeSize).Take(pgeSize).ToList();

        return result;
    }

控制器

   public ICollection<CompanyStatDomainModel> GetRecordsByPageSize(int page)
   {
       var companyStatService = new CompanyStatService();

       return companyStatService.GetRecordsByPageSize(page);
   }

WebApiConfig.cs

     var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);

【问题讨论】:

  • 您是否已将其缩小到格式问题?在return result; 上设置断点。您目前有有效的收藏吗?
  • 是的,我有,结果返回所有三个表。但是 json 结果只显示父表的数据。
  • 尝试将您的方法调用更改为public IHttpActionResult GetRecordsByPageSize(int page),而不是返回ICollection&lt;T&gt;。然后,返回以下内容 => return Ok(result); 让我知道这是否有影响?
  • 我已经这样做了,但我收到了一个错误。请看下面 //按页面大小获取记录 public IHttpActionResult GetRecordsByPageSize(int page) { const int pgeSize = 20; var result = _companyStatRepo.AllIncluding(c => c.CompanyDomainModel, c => c.RatingDomainModels) .OrderBy(c => c.CompanyStatId).Skip(page * pgeSize).Take(pgeSize).ToList();返回确定(结果); }
  • 错误是什么?分享你的js代码

标签: asp.net angularjs web-services entity-framework-6 asp.net-web-api2


【解决方案1】:

解决此类问题的最简单方法是将 EF 查询的结果手动投影到所需的结构,例如

var result = _companyStatRepo
  .AllIncluding(c => c.CompanyDomainModel, c => c.RatingDomainModels)
  .OrderBy(c => c.CompanyStatId).Skip(page * pgeSize)
  .Take(pgeSize).Select(csr => new CompanyStatRepo {
     prop1 = csr.prop1,
     prop2 = csr.prop2,
     ...
     RatingDomainModels = csr.RatingDomainModels.ToList()
  }).ToList();

我不知道你的类的真正结构,但这是基本思想。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多