This article demonstrates querying related entities using OData. The ContosoUniversity sample is used for the starter project. A malicious or naive client may construct a query that consumes excessive resources. Such a query can disrupt access to your service. The preceding code enables OData queries and returns enrollment entities SchoolContext. OData expand functionality can be used to query related data. For example, to get the Course data for each Enrollment entity, include?
Expand can be applied to more than one level of navigation property. For example, to get the Department data of each Course for each Enrollment entity, include?
The following JSON shows a portion of the output:. By default, Web API allows the maximum expansion depth of two. Create a new class named MyExpandValidator with the following code:. The preceding code creates the MyEnableQuery attribute. Skip to main content. Exit focus mode. Enable OData Update Startup. Use this method to add services to the container. SetCompatibilityVersion CompatibilityVersion. UseHttpsRedirection ; app. EnableDependencyInjection ; routeBuilder.
AddOData ; to enable OData middleware. Calls routeBuilder. Select to enable querying related entities with OData. Install Postman Start the web app. Start Postman.The OData metadata, a machine-readable description of the data model of the APIs, enables the creation of powerful generic client proxies and tools. Some of them can help you interact with OData even without knowing anything about the protocol.
The following 6 steps demonstrate 6 interesting scenarios of OData consumption across different programming platforms. But if you are a non-developer and would like to simply play with OData, XOData is the best start for you. The sample service used is the TripPin service which simulates the service of an open trip management system. Our friend, Russell Whyte, who has formerly registered TripPin, would like to find out who are the other people in it.
Want to contribute code snippet for another platform or suggest changes to this content? You can edit and submit changes to "Understanding OData in 6 steps" on its Github repository. REST principles also say, that every resource is identified by a unique identifier. OData also enables defining key properties of a resource and retrieving it using the keys.
In this step, Russell wants to find the information about himself by specifying his username as the key. For that, OData defines a series of system query options that can help you construct complicated queries for the resources you want. With the help of that, our friend Russell can find out the first 2 persons in the system who have registered at least one trip that costs more thanand only display their first name and last name.
REST principles require the using of simple and uniform interfaces. With that regard, OData clients can expect unified interfaces of the resources. After having gone through the first 3 steps, Russell thinks the system is useful.
He wants to add his best friend Lewis to the system. He finds out that all he needs to do is to send a POST request containing a JSON representation of Lewis' information to the same interface from which he requested the people information. For that, the concept of relationships in OData can be defined among resources to add flexibility and richness to the data model.
For example, in the TripPin OData service, people are related to the trips that they've booked using the system. Knowing that, Russell would like to invite Lewis to his existing trip in the U. For that purpose, OData supports defining functions and actions to represent such operations. They are also resources themselves and can be bound to existing resources.
Sample: Build web APIs with OData support using ASP.NET Core
After having explored the TripPin OData service, Russell finds out that the it has a function called GetInvolvedPeople from which he can find out the involved people of a specific trip. He invokes the function to find out who else other than him and Lewis goes to that trip in the U. Toggle navigation. For x. FindEntriesAsync ; The client library used is the Simple. The code is contributed by Vagif Abilov. The code is contributed by Bin Xu.
The code is contributed by Mark Peterson. Contribute to "Understanding OData in 6 steps" Want to contribute code snippet for another platform or suggest changes to this content? Step 2: Requesting an individual resource REST principles also say, that every resource is identified by a unique identifier.
ByKey userName : "russellwhyte". Key "russellwhyte". FindEntryAsync ; Assert. Equal "russellwhyte"person.NET Framework 4. It provides certain query options through which the on demand data can be fetched from the server by the client over HTTP. The following is the definition from ASP. NET :. OData provides a uniform way to query and manipulate data sets through CRUD operations create, read, update, and delete. More elaborated from :. The client sends these parameters in the query string of the request URI.
The OData specification calls these parameters query options. This gives you a convenient way to add features such as filtering and sorting to any Web API application. Suppose our product table in the database contains more than products and we want to fetch only the top 50 products based on certain conditions like product id or price or name. Another option could be that I fetch the data at server only and filter the same and send the filtered data to client. In both the cases I am bearing the cost of writing extra code for filtering the data.
Here is where OData comes into the picture. OData allows you to create services that are queryable. If the endpoints of the exposed services are OData enabled, or supports OData query options then the service implementation would consider the OData request and process it accordingly. So had that request for 50 records been an OData request, the service would have fetched only 50 records from the server.
Not only filtering, but OData provides features like searching, sorting, skipping the data, selecting the data too. OData -Version 4. Note that, since we are using VS and. NET framework 4. The command will download few dependent packages and reference the DLL in your project references. Our project is set to make OData endpoints. You can create new services. This method fetches all the product records from the database.
The following is the code:. Since our product Controller is secured, we need to get an authenticated token from the service and use the same to access product Controller methods.
To read about WebAPI security, refer to this article. Just add a header with the request. The header should be like:. Just save that token for making further calls to product Controller. Add an attribute named [Queryable] above the method and in Request.
CreateResponse mark the productEntities to productEntities. Here in the above endpoint, I have just appended "? This statement means that I want to fetch only the top two products from the service and the result is:. We get only two products.
So you can see here that it was very simple to make a service endpoint queryable and we did not have to write a new service to achieve this result.
Let us try few more options.The Web API implementation does supports a lot of features from the standard, but not all. For this example, an IIS hosted web application is used. Once the project has been created, open the NuGet packages and update all packages in the project.
Then attach this file to your Microsoft SQL server Microsoft SQL Server could also be used. Once the database is attached and running, you can create an entity model from the database.
OData FAQs: Why Should REST API Developers Use OData?
In the Visual Studio project, create a new folder. Click Add a new item. Choose the data menu and add ADO. Add and test your connection string. Now choose Code First from Database The database already exists. Select all the tables from the Person schema. Now all entities from the Person schema will be added to the DomainModel.
Next step is to add an OData Controller. Be careful not to use the old V3 packages. All entities from the person schema are added. These will be used in later posts. Only the Person Entity is required for the PersonController.
The OData configuration has been removed to its own method. This is different to OData V3. You have more control. Now that the OData V4 service is up and running, in the following posts, we want to explore some of the new features and also features which existed in V3 as well.
OData are the V3 libraries. Reblogged this on Dinesh Ram Kali. Cool post! What I want to do is the following: have a controller with two different methods and give all two methods a different route like I can do in ApiController. This is not working for me. I think I am understanding something completely wrong!
Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. While looking into some web services, I ran across this "new" technology that Microsoft is calling OData.
Could someone please help me understand the differences? I wrote a post on the subject a while ago here. However, they have layered some functionality on top and unfortunately have ignored some of the REST constraints in the process. The querying capability of an OData service requires you to construct URIs based on information that is not available, or linked to in the response.
It is what REST people call out-of-band information and introduces hidden coupling between the client and server. The other coupling that is introduced is through the use of EDMX metadata to define the properties contained in the entry content. Again, the client needs to know this in advance, it cannot be discovered. Unfortunately, Microsoft did not see fit to create media types to describe these key pieces of data, so any OData client has to make a bunch of assumptions about the service that it is talking to and the data it is receiving.
The OData protocol is built on top of the AtomPub protocol. REST is a generic design technique used to describe how a web service can be accessed. Using REST you can make http requests to get data. If you try it in your browser it would be just like going to a website except instead of returning a web page you would get back XML. ODataV4 follows rest principles. For example, asp. The point of Odata is being able to query directly from the URL with out-of-the-box options.
From the OData documentation :. The OData Protocol is different from other REST-based web service approaches in that it provides a uniform way to describe both the data and the data model. The OData metadata, a machine-readable description of the data model of the APIs, enables the creation of powerful generic client proxies and tools. Some of them can help you interact with OData even without knowing anything about the protocol. The following 6 steps demonstrate 6 interesting scenarios of OData consumption across different programming platforms.
But if you are a non-developer and would like to simply play with OData, XOData is the best start for you. Resource based means that data and functionalities are considered as resources. OData is a web based protocol that defines a set of best practices for building and consuming RESTful web services.
Learn more. Asked 10 years ago. Active 1 year, 5 months ago. Viewed k times. Scott Scott One is producer, the other is enabler for the consumers. Active Oldest Votes. Daniel Eisenreich 1 1 gold badge 8 8 silver badges 29 29 bronze badges. Darrel Miller Darrel Miller k 28 28 gold badges silver badges bronze badges. I was having DNS issues. It should be working now.If you're reading this article, there's a good chance you already know about oData - what it is and why you want to use it.
It standardizes certain query operations like limiting number of returned objects, performing paging, counting returned elements, selecting objects based on conditions and many more.
OData is an open protocol and is gaining support from number of information providers like SalesForce, Netflix and others. There are a number of good introductory articles on oData like this one. The code presented in this article is simple and even if you don't know much about oData but are familiar with REST or even Web Services in general, you should be able to understand how simple it is to use oData.Add OData support to your REST AP
For this article, we'll be exposing movies via oData. A Movie has an idtitleratinglast-modified-timestampdirector.
Rating is an enumeration of stars from one to five, director is a Person which has a first-name and a last-name. These classes make up the 'model' of our application.
In this article, we'll use ASP. We are explicitly specifying the version here. You may not be needed. As of this writing, 5. Having said that, the oData team seems to be changing some classes and even removing some like EnititySetManager which was present in earlier version so locking down the version will ensure that the project will work even if new version of oData is released. First, we'll add the model classes which are MoviePerson and an enum called StarRating.
It's a good idea to create these. Routing refers to understanding the URL format and translating that to method calls. Replace the existing code in the Register method with:. We'll have a thin business layer which will provide services to store and retrieve model objects, i.
Create a new folder called Business. Create a new file named DataService. Instead of actually storing the data in a database, we'll just work with an in memory list of model objects. In order to serve oData request, we need to create a controller class. A controller is responsible for managing a resource, for us, the resource is the movie collection.This document fits best the readers who has a relative good knowledge of OData e.
This document also assumes that the readers know how to create projects in Visual Studio and know how to install packages using the Nuget Package Manager. It also assumes they have knowledge in C programming and are not unfamiliar with concepts like classes, properties, methods, and so on. Then it steps into the section about how OData models can be built in different ways.
After that, OData routing is introduced in details followed by a description of OData feature implementation. Finally, it talks about security and customization of the OData V4 service. It has one entity set Productsone entity type Product. The service is read only.
The only data clients can get besides the service document and metadata document, is the Products entity set. NET Web Application template. In the New Project dialog, select the Empty template. Click OK.
In the Nuget Package Manager, install Microsoft. We also defined a Get method that returns the list of products. Replace the existing Register method with the following code:. Start the OData service by running the project and open a browser to consume it. The data model is the basis of an OData service.
In Microsoft ASP. The basic code structure to build an Edm model explicitly is shown as:. The Edm Model built by this way is called un-typed or typeless, week type Edm model. Owing that there is no corresponding CLR classes.
The developer should take all responsibility to add all Edm types, operations, associations, etc into the data model one by one.
The basic code structure of this way is shown as:. To build an Edm model using convention model builder is to create an IEdmModel object by a set of conventions. Such conventions are pre-defined rules in Web API OData to help model builder to identify Edm types, keys, association etc automatically, and build them into the final Edm model. ODataConventionModelBuilder wrappers these conventions and apply them to the Edm model when building.
Each section is designed to walk you through every required aspect to build such Edm model. This is a Customer-Order business model, in which three entity types, two complex types and one enum type are included.