bigscal-logo
  • bigscal-logo
  • Services
    • Software Development
          • Software Product Development
            • SaaS Consulting
            • MVP Development
            • Startup Product Development
            • Product UI/UX Design
            • Startup Consulting
          • Information Technology Consulting
            • Agile Consulting
            • Software Consulting
            • Data Analytics Consulting
            • CRM Consulting
          • Software Outsourcing
            • IT Staff Augmentation
            • Dedicated Development Teams
            • Shadow Engineers
            • Offshore Software Development
            • Offshore Development Center
            • White Label Services
          • Custom Software Development
            • Enterprise Software Development
            • Nearshore Software Development
          • Digital Transformation
    • Application Development
          • Mobile App Development
            • React Native App Development
            • iPhone app development
            • Android App Development
            • Flutter App Development
            • Cross Platform App Development
            • Xamarin App Development
          • Web Development
            • Website & Portal Development
          • Frontend Development
            • Angular Development
            • React.js Development
            • Next.js Development Services
          • Full Stack Development
            • MEAN Stack Development
            • MERN Stack Development
          • Backend Development
            • .NET Development
            • Node js Development
            • Laravel Development
            • PHP Development
            • Python Development
            • Java Development
            • WordPress Development
            • API Development
            • SharePoint Development
          • Cloud Application Development
            • Serverless Software Development
          • Application Maintenance
          • Application Modernization
    • QA & Testing
          • Penetration Testing
          • Usability Testing
          • Integration Testing
          • Security Testing
          • Automated Testing
          • Regression Testing
          • Vulnerability Assessment
          • Functional Testing
          • Software Performance Testing
          • QA Outsourcing
          • Web Application Testing
          • Software Quality Assurance Testers
          • Mobile App Testing
          • QA Consulting
          • Application Testing
    • eCommerce
          • eCommerce Web Design
          • Ecommerce Consulting
          • Digital Consulting
          • eCommerce Web Development
          • Supply Chain Automation
          • B2C eCommerce
          • B2B Ecommerce
    • Analytics & DevOps
          • Big Data Consulting
          • Business Intelligence Consulting
          • Microsoft Power BI
          • Power BI Implementation
          • DevOps Consulting
          • Amazon AWS
          • Microsoft Azure
    • Generative AI Development Services
          • Agentic AI Services
          • AI-ML Developers
          • Hire AI Developers
          • Machine Learning Developers
          • Deep Learning Development
          • IoT Developers
          • Chatbot Developers
  • Industries
    • Education & eLearning
    • Finance
    • Transportation & Logistics
    • Healthcare
      • Hospital Management Software Development
      • Patient Management Software Development
      • Clinic Management System
      • Telemedicine App Development Solutions
      • EMR Software
      • EHR Software
      • Laboratory Information Management Systems
    • Oil and Gas
    • Real Estate
    • Retail & E-commerce
    • Travel & Tourism
    • Media & Entertainment
    • Aviation
  • Hire Developers
    • Mobile Developers
          • Hire Android App Developers
          • Hire iOS App Developers
          • Hire Swift Developers
          • Hire Xamarin Developers
          • Hire React Native Developers
          • Hire Flutter Developers
          • Hire Ionic Developers
          • Hire Kotlin Developers
    • Web Developers
          • Hire .Net Developers
            • Hire ASP.NET Core Developers
          • Hire Java Developers
            • Hire Spring Boot Developers
          • Hire Python Developers
          • Hire Ruby On Rails Developers
          • Hire Php Developers
            • Hire Laravel Developers
            • Hire Codeigniter Developer
            • Hire WordPress Developers
            • Hire Yii Developers
            • Hire Zend Framework Developers
          • Hire Graphql Developers
    • Javascript Developers
          • Hire AngularJs Developers
          • Hire Node JS Developer
          • Hire ReactJS Developer
          • Hire VueJs Developers
    • Full Stack Developers
          • Hire MEAN Stack Developer
          • Hire MERN Stack Developer
    • Blockchain & Others
          • Hire Blockchain Developers
          • Hire Devops Engineers
          • Hire Golang Developers
  • Blogs
  • Careers
  • Company
    • Our Portfolio
    • About Us
    • Contact
  • Inquire Now
  • Menu Menu
Home1 / Backend2 / How to use OData in .net core?
Get Started with OData in .Net Core!

How to use OData in .net core?

January 26, 2022/0 Comments/in Backend /by Aayushi Ghaswala

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 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. Before diving into more, let’s learn about OData.

Integrated entity data model (EDM) that helps to depict the entered information in the methodical format.The Odata has diverse options for different data purposes including $orderby, $top, $filter, $select, and $ expand. Implementing OData with Web API helps to complete the tasks more quickly, retrieve information with single code or modify any object.

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 .NET Core ecosystem. So without further ado, let’s get started!

How To Use OData In .Net Core?

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 API like 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 start by creating one sample describing the use of OData in the .net core API, or you can say .Net Core OData 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

  • Go to Nuget Package Manager in Visual Studio and install Microsoft AspNet Core OData.
  • In VS code, go to the terminal and execute dot net add package MicrosoftAspNetCore.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 routes for OData and build an 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:
        • /api/Product?$select=Name,Price
      • 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
    • 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)
    • 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
    • OrderBy

      • Order by allow to order return collection from service.
        • /Odata/Product?$orderby=Name asc, price desc

Conclusion

In conclusion, OData presents a robust, standardized approach to integrating data-driven functionalities into .NET Core applications. Throughout this comprehensive guide, we’ve explored the essence of OData, from its fundamental concepts to its advanced features, providing you with the knowledge and tools needed to leverage this technology effectively.

By understanding OData’s query syntax and HTTP-based protocol, you can expose, consume, and interact with data seamlessly over the web. You’ve learned how to integrate OData effortlessly with .NET Core projects, whether you’re starting from scratch or enhancing existing APIs. Additionally, the combination of OData and Entity Framework has revealed a potent duo, enabling you to expose database entities as OData endpoints easily.

FAQ

What is OData?

OData, short for Open Data Protocol, is a standardized protocol that allows the creation and consumption of queryable and interoperable APIs over the web. It enables seamless data integration and exchange between different systems and platforms.

How does OData differ from traditional APIs?

Unlike traditional APIs, OData offers a standardized query language that allows clients to request only the needed data. It also provides a metadata representation of the API, making it self-descriptive and enabling dynamic discovery of available resources.

Can I use OData with .NET Core?

Yes, absolutely! OData is well-supported in the .NET Core ecosystem. Microsoft provides libraries and tools to easily integrate OData capabilities into your .NET Core applications, allowing you to expose and consume OData-compliant APIs.

What are the key benefits of using OData?

  • Simplified querying: Clients can filter, sort, and page data directly in the query string.
  • Improved discoverability: OData APIs are self-descriptive, enabling dynamic discovery of available resources and their metadata.
  • Interoperability: OData promotes data exchange between systems, regardless of the technology stack.
  • Reusability: OData-compliant APIs can be used with minimal changes across multiple applications and platforms.

OData offers several advantages, including:

How can I secure OData endpoints in my .NET Core application?

You can secure OData endpoints using various authentication and authorization mechanisms provided by .NET Core, such as JWT authentication, OAuth, or API keys. Additionally, you can implement role-based access control (RBAC) to restrict access to specific resources based on user roles or claims.

Tags: #.NET, #.Net Core, #Asp.Net, #bigscal, #odata

You might also like

Decode the Role of Statistics in Machine Learning! How Statistics is used in Machine Learning?
Succeed in your React Interview with these tips! 10 Answers to Your React JS Interview Questions
Top 5 Github Reos To Master React JS Top 5 React Github repositories to Become a Pro React js Developer
3D Password A Complete Guide about 3D Password
Role-of-Software-Development-Company-in-Stacking-Up-SEO Role of Software Development Company in Stacking Up SEO
Front-End Framework: Beyond HTML, CSS & JavaScript Are HTML, CSS, and JavaScript Enough? (Front-end Framework)

Seeking robust and scalable software solutions?

Contact us for industry-leading development services.

Book a 30 min FREE Call

Craft your Best Agile Team

Your Project, Our Expertise - Hire a Developer Now

    Subscribe for
    weekly updates

      privacy-policy I accept the terms and conditions

      Categories

      • AI-ML-Blockchain
      • Aviation
      • Backend
      • Cloud
      • Cross Platform
      • Cyber Security
      • Database
      • DevOps
      • Digital Marketing
      • Ecommerce
      • Education Industry
      • Entertainment Industry
      • Fintech Industries
      • Frontend
      • Full Stack
      • Game Development
      • Healthcare Industry
      • Latest Technology News
      • Logistics Industry
      • Mobile app development
      • Oil And Gas Industry
      • Plugins and Extensions
      • QA & Testing
      • Real Estate Industry
      • SaaS
      • Software Development
      • Top and best Company
      • Travel industries
      • UI UX
      • Website Development

      Table of Content

      bigscal-technology
      india
      1st Floor, B - Millenium Point,
      Opp. Gabani Kidney Hospital,
      Lal Darwaja Station Rd,
      Surat – 395003, Gujarat, INDIA.
      us
      1915, 447 Broadway,
      2nd Floor, New York,
      US, 10013
      +91 7862861254
      [email protected]

      • About
      • Career
      • Blog
      • Terms & Conditions
      • Privacy Policy
      • Sitemap
      • Contact Us
      Google reviews
      DMCA.com Protection Status
      GoodFirms Badge
      clutch-widget
      © Copyright - Bigscal - Software Development Company
      Google reviews
      DMCA.com Protection Status
      GoodFirms Badge
      clutch-widget

      Stay With Us

      Are you looking for the perfect partner for your next software project?

      Google reviews GoodFirms Badge clutch-widget
      • IP Rights, Security & NDA. Full ownership and confidentiality with robust security guaranteed.
      • Flexible Contracts & Transparency. Tailored contracts with clear and flexible processes.
      • Free Trial & Quick Setup. No-risk trial and swift onboarding process.

        What is Blockchain Technology and Cryptocurrency? Explore the World of Blockchain & Cryptocurrency Unlock advanced MVC 5 secrets Advance Concept of MVC 5
        Scroll to top

        We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.

        AcceptHide notification onlySettings

        Cookie and Privacy Settings



        How we use cookies

        We may request cookies to be set on your device. We use cookies to let us know when you visit our websites, how you interact with us, to enrich your user experience, and to customize your relationship with our website.

        Click on the different category headings to find out more. You can also change some of your preferences. Note that blocking some types of cookies may impact your experience on our websites and the services we are able to offer.

        Essential Website Cookies

        These cookies are strictly necessary to provide you with services available through our website and to use some of its features.

        Because these cookies are strictly necessary to deliver the website, refuseing them will have impact how our site functions. You always can block or delete cookies by changing your browser settings and force blocking all cookies on this website. But this will always prompt you to accept/refuse cookies when revisiting our site.

        We fully respect if you want to refuse cookies but to avoid asking you again and again kindly allow us to store a cookie for that. You are free to opt out any time or opt in for other cookies to get a better experience. If you refuse cookies we will remove all set cookies in our domain.

        We provide you with a list of stored cookies on your computer in our domain so you can check what we stored. Due to security reasons we are not able to show or modify cookies from other domains. You can check these in your browser security settings.

        Other external services

        We also use different external services like Google Webfonts, Google Maps, and external Video providers. Since these providers may collect personal data like your IP address we allow you to block them here. Please be aware that this might heavily reduce the functionality and appearance of our site. Changes will take effect once you reload the page.

        Google Webfont Settings:

        Google Map Settings:

        Google reCaptcha Settings:

        Vimeo and Youtube video embeds:

        Privacy Policy

        You can read about our cookies and privacy settings in detail on our Privacy Policy Page.

        Privacy Policy
        Accept settingsHide notification only