This post is about how to perform CRUD operations with OData in ASP.NET Core. On July 2018, Microsoft OData Team is announced general availability (GA) of OData (Open OData Protocol) on ASP.NET Core 2.0.
First you need to add the reference of Microsoft.AspNetCore.OData package.
Next you need to add the model classes. For this post I am using some Movie model classes. Next you need to build the edm model, you can do this by creating a static method in the startup class. Here is the code.
Next you need to add and configure the OData services via dependency injection. You can do like this.
And configure OData endpoint like this.
You can test OData by running the application and access the https://localhost:5001/odata/$metadata. And you will be able to see metadata like this.
Next you can implement DbContext and which can be used in the OData controller.
In this post I am using In Memory database, you can use any database which is supported by EF Core. And here is the modified code with DbContext added.
And you can create a MoviesController, which can be inherited from ODataController class and implement the CRUD operations.
Next you can implement the Read operations, here is the code for reading all records and getting records by key.
You can implement Post method like this, where Movie object will be posted to the endpoint and if model state is valid, it will be inserted to the database.
And you can access the service with Postman like this.
You need to decorate complex object with FromBody attribute, otherwise it will be null always. Here is the code for PUT, PATCH and DELETE methods.
Most of the code is self explanatory, so I skipping it. :)
And if you want to enable all the OData query options like $filter, $orderby, $expand, you need to modify the endpoint configuration like this.
Which will help you to execute queries like this - https://localhost:5001/odata/movies?$filter=Genre eq 'Fiction', which will return movies with Fiction genre.
Now you can convert your existing OData services to ASP.NET Core. If you find this blog post interesting let me. There is certain issues I found while working with ASP.NET Core, like if you have normal controllers and OData controller, and you enabled swagger or Open API, you may face some Output Formatter errors, but there are workarounds available. And swagger support is not available for OData in ASP.NET Core.
Happy Programming :)
What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.