In this article we will see how to create special methods called OData Action using Dynamics 365 Finance and Operation entities. This technique is very interesting because it allows you to build methods on data entities that can be called externally to dynamics with http requests. These methods can be invoked by passing parameters, can execute business logic, and return return values.
Conceptually the idea is similar to building a custom web service. Unlike web services, it is not required to create a contract or service class. With Odata Actions it is sufficient to create a method on a data entity and decorate it with an appropriate attribute. It can therefore be considered an alternative way to create a lightweight web service to perform small actions.
The advantage of building OData Actions, beyond simplicity, is that they can easily be called externally from Postman, C#, or in Power Automate flows.
Example:
In this example the objective is to retrieve the name of an item passing the item id as a parameter.
Non instance method
To define an Odata Action method you need:
- create method in an entity
- decorate it with: [SysODataActionAttribute(‘MethodName’, false)]
MethodName -> is the name of the public expose method we can use to call it out of dynamics (in Postman or PowerApp)
true/false -> indicates whether instance method or not. In this case method has to be static
The URL to use to invoke the Odata Action is the following:
https://<D365URL>/data/<DATAENTITYNAME>/Microsoft.Dynamics.DataEntities.<METHODNAME>
Instance method
By specifying true as the second parameter of [SysODataActionAttribute(‘TestProductName’, true)] we can use ‘this’ to retrieve a specific entity record. In this case, in the URL, you have to provide the Context of the data-entity along with the call. The context identifies the unique record.
This is the URL:
https://<D365URL>/data/<DATAENTITYNAME>(dataAreaId=’DAT’, PrimaryKeyField=’value’)/Microsoft.Dynamics.DataEntities.<METHODNAME>
Complex data types
Complex data types can be specified in both input and output. Simply add the SysODataCollectionAttribute decoration attribute. The SysODataCollectionAttribute class enables OData to expose strongly typed collections from X++. This class takes in three parameters:
- The name of the parameter that is a list (Use return for the return value of the method.).
- The X++ type of the members of this list.
- The public name of the OData resource that is contained in the collection.
For example:
SysODataCollectionAttribute(“return”, Types::Record, “ListColor”)
SysODataCollectionAttribute(“InputIdList”, Types::String),