Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query OData while using alternate property names

Tags:

c#

odata

I am using Newtonsoft to change property names on the web api json output.

public class User : IEntity
{
    [Newtonsoft.Json.JsonProperty(PropertyName = "user_name"]
    public string Username { get; set; }
}

I've enabled odata query so that i can add queries to the request.

[HttpGet]
[Route("api/users")]
[EnableQuery]
public IQueryable<User> GetUser()
{
    return dbContext.DbSet<User>();
}

When i make a query using the alternate property name, it fails.

GET /api/users?$select=user_name

The query specified in the URI is not valid. Could not find a property named 'user_name'

The query works fine if I use the entity model name, Username (which is not visible to public). How can i fix this while still using Newtonsoft to handle deserialization?

like image 759
user845279 Avatar asked Feb 03 '17 03:02

user845279


People also ask

What are OData query options?

A query option can be applied to every verb except DELETE operations. The query options part of an OData URL specifies three types of information: System query options , Custom query options , and Parameter aliases .

How do I filter OData query?

You can use filter expressions in OData requests to filter and return only those results that match the expressions specified. You do this by adding the $filter system query option to the end of the OData request.

How do I join two tables in OData query?

In OData there are no "joins" like in SQL server. Relationships are represented as so called "navigation" properties. Basically properties with a value of one or multiple entities (or links to those entities). So yes, if the data is backed by a SQL table, the exact join needs to be defined on the server.

What is $value in OData?

The $value option is used to get individual properties of an Entity. There are two ways to get individual properties from an entity. We can get the response in either OData format or get the raw value of the property. We need to add method to the controller named GetProperty here property is a name of the property.


1 Answers

I've not been able to achive this with the Json.Property attribute but instead this way:

// in class WepApiConfig    
ODataModelBuilder builder = new ODataConventionModelBuilder();
var conf = builder.EntitySet<User>("users");
conf.EntityType.Property(f => f.Username).Name = "user_name";

the query

GET /api/users?$select=user_name

should work now (with my OData service it works fine)

My answer is based on the reply to this question but with minor corrections.

like image 179
jps Avatar answered Sep 23 '22 07:09

jps