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.

ASP.NET Core OData Part 2

Update: see the third post here.

Introduction

This is the second post on my series on using OData with ASP.NET Core 3. You can find the first here.

Querying

We’ve seen how we can expose an object model to OData. In the first post I used Entity Framework Core, but you don’t need to use any ORM.

Where OData really excels is in querying: you can perform LINQ-style queries over the URL. These include:

  • Filtering
  • Sorting
  • Projections
  • Pagination
  • Counting
  • Navigation property expansions

By default, when you access the entity set’s endpoint, you get all records, but you can enable querying over them. This needs to be done globally first, when you define the endpoint:

app.UseEndpoints(endpoints =>
{
    endpoints.MapODataRoute("odata", "odata", GetEdmModel(app.ApplicationServices));
    endpoints.Select().Expand().OrderBy().Filter().Count();
});

Let’s have a look at the extension methods after the route registration. Don’t worry, I will show examples in a moment.

  • The Select extension method allows projections over an entity, that is, selecting only parts of it
  • Expand is used to allow expansions, for example, while retrieving an entity, similar to what Include does in Entity Framework Core – in fact, it translates to it
  • OrderBy is self explanatory. without it you won’t be able to sort the results of your query
  • Filter is what permits querying
  • Finally, Count is used to allow returning only the count, not the actual results

These are global settings, but we also need to enable them at the configuration, per entity, when we build the EDM Data Model (the GetEdmModel method I’ve shown previously):

builder
    .EntitySet<Parent>(“Parents”)
    .EntityType
    .Select()
    .Expand()
    .OrderBy()
    .Filter()
    .Count();

Finally, we also need to enable it in the action method that returns a query (IQueryable<T>), regardless of whether or not it is wrapped in an IActionResult:

[ODataRoute]

[EnableQuery]

public IQueryable<Parent> Get()

Once we do this, we can now query the entity set on the URL, but first, we need the [EnableQuery] attribute. This is what allows us to query over the results!

If you don’t want to decorate all your action methods with [EnableQuery], we can also do this globally, for any queryable action methods:

services.AddODataQueryFilter();

This has the advantage (or disadvantage) that it applies to all methods, unless we specifically tell OData that querying is not allowed.

As for querying, we have a number of options, I’m going to show just the simplest:

Filter by a property’s value:

/odata/Parents?$filter=Name eq ‘Ricardo Peres’

Sort by one property’s values descending:

/odata/Parents?$orderby=Name desc

Select just a single property:

/odata/Parents?$select=Name

Skip 10 records and retrieve the next 5, ordered by a property:

/odata/Parents?$skip=10&$top=5&$orderby=Name

Filter by a property’s value and return the count:

/odata/Parents?$filter=contains(Name,’Peres’)&$count=true

Expand a collection property:

/odata/Parents?$expand=Children

The main keywords are:

  • $filter: used for specifying conditions
  • $orderby: for sorting, either ascending or descending
  • $select: projections
  • $top: getting only some records
  • $skip: skipping some records
  • $count: getting the count of the returned records together with them
  • $expand: expansions (include navigation properties)

Some of the options can be enhanced, for example:

Filter by several conditions:

/odata/Parents?$filter=Id eq 1 or Id eq 2

/odata/Parents?$filter=Id eq 1 and Name eq ‘abc’

Where property value is in list:

/odata/Parents$filter=Id in (1, 2)

Sort by two property’s values, one descending and the other ascending:

/odata/Parents?$orderby=Name desc,Id asc

Filtering an expansion:

/odata/Parents?$expand=Children($filter=Name eq ‘A Child’)

I won’t go through all of the possible expressions, but the full OData specification is available here.

Setting Limits

We’ve seen in the beginning, while defining the OData route, that we can tell OData what should it support (select, filter, orderby, expand). We can also define the maximum amount of records to return:

app.UseEndpoints(endpoints =>
{
    endpoints.MapODataRoute("odata", "odata", GetEdmModel(app.ApplicationServices));
    endpoints.Select().Expand().OrderBy().Filter().Count().MaxTop(100);
});

Notice the MaxTop extension method, it defines the global maximum amount of records that can be returned by an OData endpoint. But we can also configure it on the action method, using the [EnableQuery] attribute:

[ODataRoute]

[EnableQuery(MaxTop = 10)]

public IQueryable<Parent> Get()

The [EnableQuery] attribute allows you to define a lot of other restrictions:

All of these options can also be specified through the AddODataQueryFilter extension method, but for global restrictions. It is at least advisable to define a maximum number of return records (MaxTop) and also the maximum number of expansions (MaxExpansionDepth).

Return Result

Querying will work both if you are returning an IQueryable<T> collection or an IEnumerable<T>. The thing is, with the former, your query will be executed in the server (the database), whereas with the latter, it will be executed in memory (LINQ to Objects). You will still be able to query, but it won’t be the same!

Inspecting Query Options

In your action methods, whenever querying is allowed, we have a way to get the query options passed to the URL ($filter, $orderby, etc), and then choose whether or not we want to apply them. The key lies in the ODataQueryOptions<T> class:

[ODataRoute]
[EnableQuery]
public IQueryable<Parent>Get(ODataQueryOptions options)
{
if (options.Top != null && options.Top.Value == 0) { options.Top.Value = 10; } var parents = _ctx.Parents.AsQueryable(); parents = options.ApplyTo(parents) as IQueryable<Parent>; return parents;
}

Here you can inspect the current filter (Filter), sort order (OrderBy), expand (SelectExpand), skip (Skip), count (Count) and even make changes. When you’re happy with then, just ApplyTo a base queryable collection.

Conclusion

This covers the basic querying options of OData. In the next post, functions and actions!

References

Please refer to the following links for additional information:

Mastering ASP.NET Core 3.0 – Second Edition

Mastering ASP.NET Core 3.0 - Second Edition

My new book, Mastering ASP.NET Core 3.0 – Second Edition, for Packt Publishing, will be available from June 19. It is a almost total rewrite from my previous one, Mastering ASP.NET Core 2.0, and it covers all of the goodies that ASP.NET Core 3.0 and 3.1 brought along. I cover Razor Pages, Blazor, OData, gRPC and some less-known features as well.

For personal reasons, it was difficult to write, and, in fact, it should have come out long ago, but, if we think about it, if it had, I wouldn’t have had the chance to cover some technologies – such as Blazor WebAssembly – that were only released recently.

I will come back to this with more information, including the table of contents, soon.

In the end, I can say that I am happy with the result, and hope you, dear readers, enjoy it too!

ASP.NET Core OData Part 1

Update: see the second post here.

Introduction

OData is an open standard for making an object-oriented domain model available as an HTTP REST interface.In a nutshell, it provides a specification for returning domain models as result of HTTP requests, querying them over the URL and even creating functions and actions over the domain model. In what .NET Core is concerned, it is a way by which you can expose your Entity Framework Core – or any other ORM that has a LINQ interface – to the web, without writing too much boilerplate code, as an ASP.NET Core Web API.

It is surprising that not many people know about OData, also, there are some caveats to it and not much documentation on using it with ASP.NET Core, so I decided to write a few posts on the subject. Here is the first!

Setting Up

Let’s pretend you have a domain model with just two classes, Parent and Child:

image

We should also have an Entity Framework Core context that exposes them:

public class ParentChildContext : DbContext

{

public ParentChildContext(DbContextOptions options) : base(options) { }

public DbSet<Parent> Parents { get; set; }

public DbSet<Child> Children { get; set; }

}

I won’t go into details as to explain this, I’m pretty sure you all know about Entity Framework Core contexts! Just make sure you add a reference to the Microsoft.EntityFrameworkCore NuGet package, or, if you’re using SQL Server, Microsoft.EntityFrameworkCore.SqlServer. Now register your context to the DI framework, in the ConfigureServices method:

services.AddDbContext<ParentChildContext>(options =>

{

options.UseSqlServer(“<connection string>”);

});

In your ASP.NET Core’s project you need to add a reference to the Microsoft.AspNetCore.OData NuGet package. This includes the server-side implementation of OData version 4 for ASP.NET Core.

You need to add its required services in the ConfigureServices method:

services.AddOData();

This registers the services, but now we need to add an endpoint for an actual domain model. ASP.NET Core OData now supports endpoint routing, so everything can be done smoothly:

app.UseEndpoints(endpoints =>

{ endpoints.MapODataRoute(“odata”, “odata”, GetEdmModel(app.ApplicationServices)); });

We registered this endpoint with name odata (first parameter) and also with the same prefix (second parameter), you can happily change this. As you can see, in this route, we are returning an EDM Data Model. We build one as this:

private static IEdmModel GetEdmModel(IServiceProvider serviceProvider)

{

var builder = new ODataConventionModelBuilder(serviceProvider);

builder.EntitySet<Parent>(“Parents”);

builder.EntitySet<Child>(“Children”);

return builder.GetEdmModel();

}

One thing that you’ll notice is that this is a conventions-based model builder, ODataConventionModelBuilder. this one takes care of some things for you, such as inferring the id property for each entity, that’s why you don’t have to explicitly state it. If your entity has an id property with a funny name, other than Id or EntityId, then you will need to specify it:

builder

.EntitySet<Parent>(“Parents”)

.EntityType

.HasKey(x => x.Id);

There is no need to specify the other properties, because they are all inferred automatically too from the generic parameter.

Do keep in mind the entity set name that you give, it is common to have a pluralized form of the entity name, but it is not required.

Now we need to create a controller that exposes this. At the very least, we will need two methods:

[ODataRoutePrefix(“Parents”)]

public class ParentController : ODataController

{

private ParentChildContext _ctx;

public ParentController(ParentChildContext ctx)

{

this._ctx = ctx;

}

[ODataRoute]

public IQueryable<Parent> Get()

{

return this._ctx.Parents.AsQueryable();

}

[ODataRoute(“{id}”)]

public Parent Get([FromODataUri] int id)

{

return this._ctx.Parents.Find(id);

}

}

This controller is specific to the Parents entity set, so, if you wish, you need to have another one for the Children. This is specified in the [ODataRoutePrefix] attribute.

Also notice how we are returning IQueryable<Parent> from the Get action method that does not take parameters and a single Parent from the other. You can also declare IActionResult or ActionResult<T>:

[ODataRoute]

public IActionResult Get()

{

return this.Ok(this._ctx.Parents.AsQueryable());

}

//alternative

[ODataRoute]

public ActionResult<IQueryable<Parent>> Get()

{

return this.Ok(this._ctx.Parents.AsQueryable());

}

The latter, the one that uses ActionResult<T>, has some advantages, which you can read about here.

And, of course, all of the methods can be made asynchronous too:

[ODataRoute]

public async Task<IQueryable<Parent>> Get()

{

return await this._ctx.Parents.ToListAsync();

}

[ODataRoute(“{id}”)]

public async Task<Parent> Get([FromODataUri] int id)

{

return await this._ctx.Parents.FindAsync(id);

}

We will see a problem with the implementation of the first method in the next post.

Now, the first method, the one without parameters, returns all of the entities in the database, and the second, as one would expect, returns possibly one from its id property.

Conclusion

We’re all done here, so we can now access the endpoints we just created, try to navigate to the following URLs:

  • /odata: returns information about the exposed entity sets (Parents and Children)

image

  • /odata/parents –> ParentController.Get(): returns all records for the Parent entity
  • /odata/parents(1) –> ParentController.Get(1): returns possibly one record, if it exists in the database for the given primary key of the Parent entity

This is the very basics, in the future posts we will explore other options, such as querying over the URL and creating functions and actions.

References

You can find more information in the following pages: