ASP.NET Core OData Part 3

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

内容简介: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.


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

查看所有标签

猜你喜欢:

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

互联网的基因

互联网的基因

人民邮电出版社 / 2016-9-21 / 48.00元

《互联网的基因》是一本从电信看互联网创新,从互联网看电信创新的力作。作者何宝宏博士长期在电信行业从事互联网领域研究,是极为少有的“既懂IP又懂电信”的专家。该书借以电信和互联网技术创新的大脉络,用轻松、诙谐、幽默的语言,结合经济学、社会学、哲学、人类学甚至心理学理论,揭示互联网、云计算、大数据以及目前最热门的区块链等技术发展背后的规律。作者在该书中明确表示,互联网是新的技术物种,互联网有基因,互联......一起来看看 《互联网的基因》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

MD5 加密
MD5 加密

MD5 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具