ASP.NET Core OData Part 3

Introduction

This will be the third post on OData and ASP.NET Core 3. Please find the first post (basics) here and the second post (querying) here. This time, I will talk about actions and functions. For demo purposes, let’s consider this domain model:

ClassDiagram1

Functions

A function in OData is like a pre-built query that may take some parameters and either return a single value or a collection of values, which may be entities. An action is similar, but, unlike functions, an action can have side effects, that is, it can make modifications to the underlying data.

Some examples of function calls might be

  • /odata/blogs/FindByDate(date=2009-08-01) – returning a collection of entities
  • /odata/blogs/CountPosts(blogid=1) – returning a single value
  • /odata/blogs/Blog(1)/Count – returning a single value
  • /odata/CountBlogPosts – returning a single value

As you can see in these example links, most of them are associated with the "blogs" entity set, these are called bound functions, but one of them is not, it is therefore an unbound function.

Registering these functions can be a bit tricky because there are a few things involved:

  • The [ODataRoutePrefix] attribute in a controller
  • The way we define the function when we build the EDM Data Model
  • The [ODataRoute] applied to the action method

But I digress. Let’s start with the first function.

Bound Function with Parameters Returning a Collection of Entities

For this we need to define a function in our model, associated with an entity set:

var findByCreation = builder
    .EntitySet<Blog>("Blogs")
    .EntityType
    .Collection
    .Function("FindByCreation");
findByCreation.ReturnsCollectionFromEntitySet<Blog>("Blogs"); findByCreation.Parameter<DateTime>("date").Required();

This will register a function named FindByCreation in the Blogs entity set, which returns a collection of Blog entities and takes a parameter of type DateTime named date.

Its implementation in a controller is:

[ODataRoutePrefix("Blogs")]
public class BlogController : ODataController
{
    private readonly BlogContext _ctx;

    public BlogController(BlogContext ctx)
    {       
this._ctx = ctx;
    }

[EnableQuery]
[ODataRoute("FindByCreation(date={date})")]
    [HttpGet]
    public IQueryable<Blog> FindByCreation(DateTime date)
    {
        return _ctx.Blogs.Where(x => x.Creation.Date == date);
    }
}

Notice the Blogs prefix applied to the BlogController class, this ties this class to the Blogs entity set.

The [EnableQuery] attribute, discussed on the previous post, allows the results of this function to be queried too.

Now you can browse to https://localhost:5001/odata/blogs/FindByCreation(date=2009-08-01) and see the results!

Bound Function with Parameters Returning a Single Value

Another example, this time, returning a single value:

var countPosts = builder
    .EntitySet<Blog>("Blogs")
    .EntityType
    .Collection
    .Function("CountPosts");

countPosts.Parameter<int>("id").Required();
countPosts.Returns<int>();

The function CountPosts is registered to the Blogs entity set, taking a single required parameter named id.

As for the implementation, in the same BlogController:

[ODataRoute("CountPosts(id={id})")]
[HttpGet]
public int CountPosts(int id)
{
    return _ctx.Blogs.Where(x => x.BlogId == id).Select(x => x.Posts).Count();
}

This will be available as https://localhost:5001/odata/blogs/CountPosts(id=1)

Unbound Function

Next up, an unbound function, that is, one that is not associated with an entity set:

var countBlogPosts = builder.Function("CountBlogPosts");
countBlogPosts.Returns<int>();

This function, as you can see, is not attached to any entity set.

Its implementation must be done in a controller that is also not tied to any entity set (no [ODataRoutePrefix] attribute):

public class BlogPostController : ODataController
{
private readonly BlogContext _ctx;

public BlogPostController(BlogContext ctx)
{
this._ctx = ctx;
}

[HttpGet]
[ODataRoute("CountBlogPosts()")]
    public int CountBlogPosts()
{
return _ctx.Posts.Count();
}
}

And to call this function, just navigate to https://localhost:5001/odata/CountBlogPosts().

Actions

The difference between actions and functions is that the former may have side effects, such as modifying data. It should come as no surprise, following REST principles, that actions need to be called by POST or PUT. Let’s see a couple examples

Bound Function with Key Parameter and No Payload Returning a Single Value

Here we want the URL to reflect the fact that we are invoking this function on a specific entity. The definition of the function in the EDM Data Model is:

var count = builder
    .EntitySet<Blog>("Blogs")
    .EntityType
    .Collection
    .Action("Count");
count.Parameter<int>("id").Required(); count.Returns<int>();

Now we are using Action instead of Function to define the Count action!

As for the definition:

[ODataRoute("({id})/Count")]
[HttpPost]
public int Count([FromODataUri] int id)
{
    return _ctx.Blogs.Where(x => x.BlogId == id).Select(x => x.Posts).Count();
}

Notice that we applied the [FromODataUri] attribute to the id parameter, this is required.

To call this action, you will need to POST to https://localhost:5001/odata/blogs/Blog(1)/Count.

Bound Function with Key Parameter and Payload Returning an Entity

The difference between this one and the previous is that this receives an entity as its payload. The definition first:

var update = builder
    .EntitySet<Blog>("Blogs")
    .EntityType
    .Collection
    .Action("Update");

update.EntityParameter<Blog>("blog").Required();
update.ReturnsFromEntitySet<Blog>("Blogs");

Notice how I replaced Parameter by EntityParameter.

The action method implementation is:

[ODataRoute("({id})/Update")]
[HttpPost]
public Blog Update([FromODataUri] int id, ODataActionParameters parameters)
{
var blog = parameters["blog"] as Blog;
_ctx.Entry(blog).State = EntityState.Modified;
_ctx.SaveChanges();
    return blog;
}

And to call this, you need to POST to https://localhost:5001/odata/blogs(1)/Replace with a payload containing a blog property with a value that is the Blog that you wish to update:

{
    "blog" : {
        "BlogId": 1,
        "Name": "New Name",
        "Url": "http://blog.url",
        "CreationDate": "2009-08-01"
    }
}

Conclusion

This concludes the topic of functions and actions. On the next post I will be talking about some more advanced features of OData.

                             

6 Comments

  • Hi and thanks for sharing these wonderful articles.

    Is there a way to share property attributes over the wire using OData or any other way, so we can utilize them in the client side as well?

  • Shimmy: sure, you can share the data model between the client and the server. I will make available all of the code very soon, stay tuned!

  • Hello Ricardo,

    I am making a software ( based on blockly) that can interact with OData in the form of blocks.
    Please give feedback and possible improvements https://netcoreblockly.herokuapp.com/ , see Odata links 26, 27,28,29

  • Code sample available here: https://github.com/rjperes/odata/

  • First of all I like your Odata blog articles. It is easy to understand and well explained

    I liked to see a blog post about mapping DTO to DAO objects of entity framework. How would you set this up? Maybe utilizing Automapper projections with Explicit expansion?

  • Hi, Riaz! Yes, it's common to see that. It's not related to OData, so maybe I'll cover it in another post! :-)

Add a Comment

As it will appear on the website

Not displayed

Your website