ASP.NET Core OData Part 3

栏目: IT技术 · 发布时间: 4年前

内容简介: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:A function in OData

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:

ASP.NET Core OData Part 3

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 theprevious 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)

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 => 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.


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

架构整洁之道

架构整洁之道

【美】Robert C. Martin(罗伯特 C. 马丁) / 电子工业出版社 / 2018-9 / 99.00元

《架构整洁之道》是创造“Clean神话”的Bob大叔在架构领域的登峰之作,围绕“架构整洁”这一重要导向,系统地剖析其缘起、内涵及应用场景,涵盖软件研发完整过程及所有核心架构模式。《架构整洁之道》分为6部分,第1部分纲领性地提出软件架构设计的终极目标,描述软件架构设计的重点与模式;第2~4部分从软件开发中三个基础编程范式的定义和特征出发,进一步描述函数、组件、服务设计与实现的定律,以及它们是如何有效......一起来看看 《架构整洁之道》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

随机密码生成器
随机密码生成器

多种字符组合密码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具