Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic web api odata metadata additional properties

In web api odata that uses v4 protocol, how to add additional attributes?

fully dynamic, no entity framework, no reflection providers,
metadata is dynamically generated when url is called.

Edit
Web Api Request url:
http://locahost/Service1/EntitySet1

Actual json output:

{"@odata.context":"some url", value:[{"id":1}]}  

Expected json response:

{"@odata.context":"some url", value:[{"id":1}], "ExtraCustomAttribute": "custom value"}  

How to add this custom attribute in response web api odata v4 json?

In both metadata call (edmx response) and instance payload call (json response)).

like image 546
Navaneeth Avatar asked Nov 10 '22 23:11

Navaneeth


1 Answers

In OData v4 there are at least two options to implement that behavior: an open type, Instance Annotations. It's depends on your requirements or design decisions.

The open type was added as a stuctured type that contains dynamic properties, in addition to any properties that are declared in the type definition. Open types let you add flexibility to your data models.

This tutorial:

http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/use-open-types-in-odata-v4

shows how to use open types in ASP.NET Web API OData.

Instance Annotations are described here: docs.oasis-open.org/odata/odata-json-format/v4.0/os/odata-json-format-v4.0-os.html#_Toc372793088

In your case try to declare you entity as:

ODataModelBuilder builder = new ODataModelBuilder();

ComplexTypeConfiguration<YourEntity> pressType = builder.ComplexType<YourEntity>();
// ...
pressType.HasDynamicProperties(c => c.ExtraCustomAttribute);
// public IDictionary<string, object> ExtraCustomAttribute{ get; set; }

and in get action method generate entity as you wish. Another option is available to get control over entry serialization, check here

https://aspnetwebstack.codeplex.com/wikipage?title=OData%20formatter%20extensibility

like image 192
Oleg Tamarintsev Avatar answered Jan 04 '23 03:01

Oleg Tamarintsev