How to use OData in .net core?
Quick Summary: OData, the Open Data Protocol, revolutionizes data integration and exchange by providing a standardized way to create and consume queryable APIs over the web. In this guide, we focused on using OData in .NET Core; developers gain insights into its fundamental concepts and seamless integration within the .NET Core ecosystem. The article will showcase how OData can be used with Entity Framework for data manipulation. Additionally, the guide emphasizes Securing OData in .Net Core endpoints and offers optimization tips!
Introduction
Data is the backbone of every successful application in today’s fast-paced digital era. As developers strive to build more efficient, scalable, and user-friendly solutions, seamless data integration and query capabilities are essential. It is where OData, short for Open Data Protocol, emerges as a game-changing technology, providing a standardized way to expose, consume, and interact with data over the web.
There is a possibility that you might have heard about it somewhere. If you’re a .NET Core developer or own a company, hire the best .NET Core developers and harness the full potential of OData. Take your data-driven applications to the next level. You’ve come to the right place.
In this article, we’ll explore OData, exploring its fundamental concepts and learning how to implement it effectively within the OData client .net core ecosystem. So without further ado, let’s get started!
How To Use OData In .Net Core?
The OData in asp.net core usage: OData stands for Open Data Protocol which helps to build and consume RESTFul APIs. It is an ISO/IEC-approved and OASIS standard. OData will take care of various approaches to RESTful APIs. The APIs such as Status codes, URL conventions, request and response headers, media types, query options, payload formats, etc. So as a developer, you can only focus on your business logic. It provides instructions for defining functions/actions for reusable procedures, tracking changes, and sending asynchronous/batch requests. Let’s get started with creating one sample that describes the use of OData in the .net core API.
For the testing part try Unit Testing With Xunit in .Net Core
Create a sample project
Create a sample project of Web API in Visual Studio or VS code.
Install the packages
- In Visual Studio go to Nuget Package Manager and install Microsoft.AspNetCore.OData.
- In VS code, go to terminal and execute dotnet add package Microsoft.AspNetCore.OData to add OData packages in a project.
OData using 7.5 and older versions
Register OData
Go to Startup.cs and register OData in ConfigureServices method like below and also manage route for OData and build EDM model to manage OData batch in response. We also need to enable some standard query commands like
Select -> to manage select using a query.
Filter -> manage filter on response.
Expand-> get a child and parent data into a response.
Count-> get count of data.
MaxTop-> specify a maximum number of data. Eg. If you specify maxpTop(100) then default it will only return 100 raws.
Order by -> to manage order by on a query on a query.
-
-
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddOData(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseEndpoints(endpoints => { endpoints.MapODataRoute("OData","api", GetModel()); endpoints.Select().Expand().Count().SkipToken() .MaxTop(100).Filter().OrderBy(); endpoints.MapControllers(); }); } private IEdmModel GetModel() { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); builder.EntitySet<Product>("Product"); builder.EntitySet<Category>("Category"); return builder.GetEdmModel(); } } After registering Odata on the Startup file, now need to just manage the OData attribute over API method like below in controller. [HttpGet] [EnableQuery] public IQueryable<Product> GetProducts() { return context.Products; }
- Now execute API on a browser or in postman to check the response.
-
-
Swagger error with OData
- If you are using OData with Swagger then it will break Swagger UI because Swagger by default cannot .Net Core OData handling the input and output format of OData. So to fix this with .Net Core OData error handling, issue need to define input and output OData formatter in .Net Core for OData in Configure services method of Startup.cs
-
using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.Net.Http.Headers; services.AddMvcCore(options => { foreach (var outputFormatter in options.OutputFormatters.OfType<OutputFormatter>().Where(x => x.SupportedMediaTypes.Count == 0)) { outputFormatter.SupportedMediaTypes.Add( new MediaTypeHeaderValue( "application/prs.odatatestxx-odata")); } foreach (var inputFormatter in options.InputFormatters.OfType<InputFormatter>().Where( x => x.SupportedMediaTypes.Count == 0)) { inputFormatter.SupportedMediaTypes.Add( new MediaTypeHeaderValue( "application/prs.odatatestxx-odata")); } });
OData using 8 or the latest version
For the OData versioning in .Net Core the configuration is now changed, MapODataRoute is gone but AddOData is still there. Check the below configuration for the latest version of OData services in .Net Core. Now need to just manage the basic setting in the ConfigureServices method of the startup file and the OData routing in .Net Core.
public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddOData(option => { option.Select(); option.Expand(); option.Filter(); option.Count(); option.SetMaxTop(100); option.SkipToken(); option.AddRouteComponents("Odata", GetModel()); }).AddNewtonsoftJson(); services.AddDbContext<ProductDBContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection") )); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "ODataDemo", Version = "v1" }); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ODataDemo v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } private IEdmModel GetModel() { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); builder.EntitySet<Product>("Product"); builder.EntitySet<Category>("Category"); return builder.GetEdmModel(); }
System Query Option
It is a query string parameter used to control the amount and order of data returned by API. All system query options are optionally prefixed with a dollar ($) character. It should be in lower case and prefix with $ to use in a query. OData Protocol V4.01 base service support case insensitive system query option names.
System query options are $expand, $filter, $count, $select, $top, $skip, and $orderby.
-
-
Select
- $select query options used to request a specific set of properties of each entity. It allows selecting multiple properties so a .net oData client can provide multiple values with a comma-separated list of selection clauses.
- Example:
- Response:
-
{ "@odata.context": "https://localhost:44360/Odata/$metadata#Product(Name,Price)", "value": [ { "Name": "IQZ3", "Price": 20000 }, { "Name": "Nokia 6", "Price": 15000 } ] }
-
Filter
- As the name suggests it is used to filter a collation of data that will be returned by the requested URL. It will only return data that match provided filter. Its support major operator is listed below.
-
Name Operator Use Equal eq /Odata/Product?$filter=Name eq ‘IQZ3’ Not Equal ne /Odata/Product?$filter=Name ne ‘IQZ3’ Less than lt /Odata/Product?$filter=Price lt 20000 Less than or equal le /Odata/Product?$filter=Price le 20000 Greater than gt /Odata/Product?$filter=Price gt 15000 Greater than or equal ge /Odata/Product?$filter=Price gt 15000 Logical Or or /Odata/Product?$filter=Price gt 15000 or Price le 20000 Logical and and /Odata/Product?$filter=Price gt 15000 and Price le 20000 Logical not not /Odata/Product?$filter=not startswith(Name,’I’)
- In query itself, client can also use arithmetic operator like addition (add), subtraction (sub), multiplication (mul), Division (div) and modulo (mod).
- /Odata/Product?$filter=Price add 1 gt 20000
- /Odata/Product?$filter=Price sub 1 gt 20000
- /Odata/Product?$filter=Price mul 3 gt 20000
- /Odata/Product?$filter=Price div 2 gt 20000
- /Odata/Product?$filter=Price mod 5 eq 0
- Other than the above operator, the filter will also allow to use of string function, date function match function, and type function.
- String functions: filter will allow to use of major available string functions like lower, upper, substring, indexOf, startswith, endswith, length, trim, concat and replace, etc
- /Odata/Product?$filter=tolower(Name) eq ‘nokia’
- /Odata/Product?$filter=toupper(Name) eq ‘NOKIA’
- /Odata/Product?$filter=trim(Name) eq ‘Nokia’
- /Odata/Product?$filter=concat(concat(Brand,’,’), Name) eq ‘Vivo V7’
- /Odata/Product?$filter=replace(Name,’ ‘,’’) eq ‘Nokia’
- /Odata/Product?$filter=indexof(Name,’Nokia’) eq 1
- /Odata/Product?$filter=length(Name) eq 6
- /Odata/Product?$filter=startswith(Name, ‘Nokia’) eq true
- /Odata/Product?$filter=endswith(Name, ‘z’) eq true
- /Odata/Product?$filter=substringof(‘Nokia’,Name) eq ‘Nokia’
- /Odata/Product?$filter=substring(Name,1) eq ‘Nokia’
- /Odata/Product?$filter=substring(Name,1,2) eq ‘No’
- Date Functions: Below is the date functions that are used with a filter to get data based on the date filter.
- /Odata/Order?$filter=day(OrderDate) eq 5
- /Odata/Order?$filter=hour(OrderDate) eq 10
- /Odata/Order?$filter=minute(OrderDate) eq 10
- /Odata/Order?$filter=month(OrderDate) eq 2
- /Odata/Order?$filter=second(OrderDate) eq 0
- /Odata/Order?$filter=year(OrderDate) eq 2022
- Type Functions :
- /Odata/Product?$filter=isof(Name, ‘Edm.String’) eq 0
- Math Functions: Filter will also allow to use of math functions like round, floor, ceiling.
- /Odata/Order?$filter=round(OrderPrice) eq 1000
- String functions: filter will allow to use of major available string functions like lower, upper, substring, indexOf, startswith, endswith, length, trim, concat and replace, etc
-
Expand
- Using expand client can request a related entity with a defined entity in the result set, so it will include parent and child entity with a specific entity.
- Example: /Odata/Product?$expand=category, Order
- It will also allow to use of other query options with expanded entity
- /Odata/Product?$expand=Order($filter=month(orderDate) eq 2)
- Using expand client can request a related entity with a defined entity in the result set, so it will include parent and child entity with a specific entity.
-
-
-
Top, Skip, and Count
- $top will return a specific number of items from the result set and $skip will skip the specific number of items from the result set and will not include in the result. Using $top and $skip, client can manage pagination. $count used to return a count of the total number of the item along with result collection.
- /Odata/Product?$top(20)
- /Odata/Product?$skip(20)
- /Odata/Product?$count=true
- $top will return a specific number of items from the result set and $skip will skip the specific number of items from the result set and will not include in the result. Using $top and $skip, client can manage pagination. $count used to return a count of the total number of the item along with result collection.
-
OrderBy
- Order by allow to order return collection from service.
- /Odata/Product?$orderby=Name asc, price desc
- Order by allow to order return collection from service.
-
Conclusion
In conclusion, this was all about integrating your node.js application into a single executable. People need to pay attention to all the steps that are important to follow.
If you find yourself stuck at any point, we can help you. Our developers at Bigscal Make sure that your task will be done successfully. So, if anything troubles you, you can connect with us directly!
FAQ
How to run node js single file?
When you are looking forward to running the Node.js program, it requires the node command that is available globally. It is only available when you have previously installed node.js. Now look at the file and pass the name for it. Make sure the file is the same as you want to execute. The directory must contain the node app/.js file you want to work with.
How to convert the js file to exe?
There are two ways through which you will be able to do it. These are as follows:
- Create a script.sh, file, and add, make it executable & add.
- Node Wallet. Js “address,” “amount” in it.
Can node JS be compiled?
Do understand this primarily that the Node. Js is compiled into machine code and built on the Google V8 engine. It makes it the best high-performance JavaScript engine written in C++. This engine successfully complies with javaScript to Machine code, allowing the CPU to execute it directly. When the same has been completed, this contributes to fast performance.
How is node js single-threaded single-threaded?
Node.Js follows a Single threaded with an event loop model. It doesn’t follow the Request/Response Multi-Threaded Stateless Model. The model is based explicitly on Javascript Event-based model with a Javascript callback mechanism.
How to create an executable?
A user will be able to create the executable file on Windows easily. But do know this one is not a simple process to follow. Users need to code the entry file for software they want to run in the chosen programming language, and then they can compile the file they wish to execute.