'How to check if a property is $select-ed?
I am building an OData web API, and I am trying to implement this function to determine whether a given property should be included in a GET response based on the $select value in the query:
bool IsPropertySelected(ODataQueryOptions options, string propertyName)
Browsing docs for ODataQueryOptions
, there is not an obvious way to do this. I have seen that the library will apply the $select
clause automatically, but this happens after the response object is generated with all the properties. Some properties are expensive to calculate, so I want to avoid this cost for any properties that are not $select
-ed.
For example, with an entity schema like:
class Foo
{
public string a {get; set;} // From data source A
public string b {get; set;} // From data source B
public string c {get; set;} // Aggregated from both data sources
}
The controller method would look something like
public async Task<Foo> GetFoo(string id, ODataQueryOptions options)
{
var result = new Foo();
bool needDataFromA = (new List { "a", "c" }).Any(x => IsPropertySelected(options, x));
bool needDataFromB = (new List { "b", "c" }).Any(x => IsPropertySelected(options, x));
if (needDataFromA && needDataFromB)
{
// get data from A and set result.a
// get data from B and set result.b
// set result.c
}
else if (needDataFromA)
{
// get data from A and set result.a
}
else if (needDataFromB)
{
// get data from B and set result.b
}
return result;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|