【问题标题】:Web API OData $expand doesn't return complex typesWeb API OData $expand 不返回复杂类型
【发布时间】:2015-08-13 09:37:21
【问题描述】:

领域模型:

public class Course
{
   public int CourseId { get; set; }
   public virtual ICollection<TeeSet> TeeSets { get; set; }
}
public class TeeSet
{
    public int TeeSetId { get; set; }
    public int CourseId { get; set; }
    public CourseRating MensRating { get; set; }
}

将课程扩展为包含 TeeSet 时,以下查询不包含 CourseRating 复杂类型。
GET /api/courses?$expand=TeeSets

public class CoursesController : ApiController
{
    [Queryable]
    public IQueryable<Course> Get()
    {
        return _uow.Courses.GetAll();
    }
}

JSON 序列化结果不包含 MensRating 复杂类型(CourseRating):

[
  {
"teeSets": [
  {
    "teeSetId": 1,
    "courseId": 7
  },
  {
    "teeSetId": 2,
    "courseId": 7
  }
   ],
   "courseId": 7,
  }
]

但是,对 DbContext 的快速测试会在 TeeSet 上返回 CourseRating 复杂类型,就像我期望的那样:

[TestMethod]
public void Get_Course_With_TeeSets()
{
    using (CoursesContext ctx = new CoursesContext())
    {
        var courses = ctx.Courses.Where(x => x.CourseId == 7).Include(x => x.TeeSets).FirstOrDefault();
    }
}

使用实体框架 6 和 Web API 2。

【问题讨论】:

    标签: entity-framework asp.net-web-api odata


    【解决方案1】:

    你应该像这样扩展MensRatingGET /api/courses?$expand=TeeSets/MensRating

    当我们构建隐式 EDM 模型以支持 QueryableAttributeApiController 时,我们将每种类型都视为实体类型,以绕过复杂类型不能引用实体类型的 OData V3 限制。而且,这意味着您必须显式扩展每个非原始类型。

    【讨论】:

    • 是的,我试过了,但是抛出了 NotSupportedException。 “无法比较 'StatTracker.Domain.CourseRating' 类型的元素。仅支持原始类型、枚举类型和实体类型。”看起来只有当包含实体通过 $expand 包含时才会发生这种情况,因为另一个包含 CourseRating 复杂类型的实体可以与 GET 或 POST 一起正常工作。
    【解决方案2】:

    MensRating 上添加AutoExpand 属性可以使这项工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-26
      • 2012-02-02
      • 1970-01-01
      • 2015-05-20
      • 2013-02-23
      • 1970-01-01
      • 2015-01-03
      • 2014-11-16
      相关资源
      最近更新 更多