0

目标:扩展一个对象,并将一个嵌套属性投影到根选择上,以及其他道具。

有如下关系:

public class Product {
   public string Barcode { get; set; }
   public double Price { get; set; }
   public Category Category { get; set; }
}

public class Category {
   public string Name { get; set; }
}

我想做一个预测,这将导致:

{
   "@odata.context": "http://localhost/odata/$metadata#Product",
   "value": [
      {
         "Price": 500,
         "Name": "Meat Products" // this is category name, ideally would be to rename it to CategoryName
      }
   ]
}

目前我在哪里得到这个:

{
   "@odata.context": "http://localhost/odata/$metadata#Product",
   "value": [
      {
         "Price": 500,
         "Category": {
            "Name": "Meat Products"
         }
      }
   ]
}

使用的查询如下:

/odata/Product?$expand=Category($select=Name)&$select=Price

我希望写一个这样的投影:

/odata/Product?$expand=Category&$select=Price,Category/Name as CategoryName

或者

/odata/Product?$expand=Category&$select=Price,Category($select=Name as CategoryName)

或者

/odata/Product?$expand=Category&$select=Price,Category($select=Name)

这是可以实现的吗?谢谢!

PS OData V4。

4

1 回答 1

1

This is not achievable with odata v4 query semantic. As you can see, the response body contains a line:

"@odata.context": "http://localhost/odata/$metadata#Product"

This is to indicate the whole response payload represents an instance of 'Product' type. Suppose 'CategoryName' property does not exist on that type, it is not possible to instruct service to dynamically add one via the 'AS' clause. And keyword 'AS' also does not exist in standard OData query spec.

However, it is indeed valid to return an additional property beyond the metadata, see Reference.

Clients MUST be prepared to receive additional properties in an entity or complex type instance that are not advertised in metadata, even for types not marked as open.

So in this case, the service could just return an additional 'virtual' property 'CategoryName' in the response. (If you're the service owner you can update response logic and do the change.) This could be a service behavior, rather than a reaction to certain client query.

于 2016-11-21T09:01:45.773 回答