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.


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

查看所有标签

猜你喜欢:

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

应用密码学

应用密码学

Bruce Schneier / 吴世忠/等 / 机械工业出版社 / 2000-1-1 / 49.00元

应用密码学:协议、算法与C源程序,ISBN:9787111075882,作者:(美)Bruce Schneier著;吴世忠 等译一起来看看 《应用密码学》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

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

多种字符组合密码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具