Web API 2.2 - Odata v4(手动解析 uri + 支出)

Web API 2.2 - OData v4 (Manually Parsing Uri + Expanding)

我有一个带有 Get 方法的 ODataController:

public IHttpActionResult Get(ODataQueryOptions<MyModel> queryOptions) {
  IQueryable<MyModel> models = _Models.AsQueryable(); // _Models Defined in Controller as List<MyModel> and is already populated with nested data for both .LevelOne and .LevelOne.LevelTwo which are two other Lists.

  Uri fullrequest = Request.GetRequestContext().Url.Request.RequestUri; // http://localhost:8080/odata/Root?$expand=LevelOne($expand=LevelTwo)
  Uri serviceroot = new Uri(controller.GetLeftPart(UriPartial.Path).Replace("/Root", "")); // http://localhost:8080/odata
  String metadata = service + "/$metadata"; // http://localhost:8080/odata/$metadata

  IEdmModel model = EdmxReader.Parse(XmlTextReader.Create(metadata));
  ODataUriParser parser = new ODataUriParser(model, serviceroot, fullrequest);
  SelectExpandClause selectAndExpand = parser.ParseSelectAndExpand();

//Only one of the two below lines is ever commented in...
  Request.ODataProperties().SelectExpandClause = queryOptions.SelectExpand.SelectExpandClause; // This line will work
  Request.ODataProperties().SelectExpandClause = selectAndExpand; // This line will not work

  return Ok(models);
}

使用我手动解析的 selectAndExpand 不会扩展数据集,但使用预定义的 queryOptions 可以。任何想法为什么?在调试器中查看时,这两个对象似乎包含相同的信息,但我一定遗漏了一些东西。我希望能够自己解析 URI,而根本不需要 ODataQueryOptions。

我最终做的是基于原始请求构建一个新的 ODataQueryOptions 对象,然后仅从中提取 SelectExpandClause。它没有回答我最初的问题,但对于不必传入 ODataQueryOptions 参数来说,它是一个有点可行的解决方案。请参阅下面的代码:

public IHttpActionResult Get() {
//Get Queryable Item (in this case just a list made queryable)
  IQueryable<MyModel> models = _Models.AsQueryable();

//Create new ODataQueryContext based off initial request (required to create ODataQueryOptions)
  ODataQueryContext selectAndExpandContext = new ODataQueryContext(Request.ODataProperties().Model, typeof(MyModel), Request.ODataProperties().Path);

//Create new ODataQueryOptions based off new context and original request
  ODataQueryOptions<Employee> selectAndExpandOptions = new ODataQueryOptions<Employee>(selectAndExpandContext, Request);

//Attach Select + Expand options to be processed
  if (selectAndExpandOptions.SelectExpand != null) {
    Request.ODataProperties().SelectExpandClause = selectAndExpandOptions.SelectExpand.SelectExpandClause;
  }

  return Ok(models);
}