Web API OData $expand doesn't return complex types

戏子无情 提交于 2019-12-22 09:02:12

问题


Domain model:

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

The following query does not include the CourseRating complex type when Courses are expanded to include TeeSets.
GET /api/courses?$expand=TeeSets

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

The JSON serialized result does not include the MensRating complex type (CourseRating):

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

However, a quick test against the DbContext returns the CourseRating complex type on TeeSets like I would expect:

[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();
    }
}

Entity Framework 6 and Web API 2 used.


回答1:


You should expand MensRating as well like this, GET /api/courses?$expand=TeeSets/MensRating

When we build an implicit EDM model for supporting QueryableAttribute with ApiController, we treat every type as an entity type to get around the OData V3 limitation that complex types cannot refer to entity types. And, this means that you have to expand explicitly every non primitive type.




回答2:


Add AutoExpand on MensRating Property can make this work.



来源:https://stackoverflow.com/questions/20137681/web-api-odata-expand-doesnt-return-complex-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!