NET Core Development Log OData (Open Data Protocol)

Time:2019-10-8

Sketch

OData, or Open Data Protocol, is an open protocol launched by the company in 2007, which aims to create and use query and interactive RESTful API in a simple and standard way.

Class library

To use the OData function in. NET Core, you need to add the Microsoft. AspNetCore. OData package.


dotnet add package Microsoft.AspNetCore.OData

Prepare model class


public class Address
{
 public string City { get; set; }
 public string Street { get; set; }
}
public enum Category
{
 Book,
 Magazine,
 EBook
}
public class Press
{
 public int Id { get; set; }
 public string Name { get; set; }
 public string Email { get; set; }
 public Category Category { get; set; }
}
public class Book
{
 public int Id { get; set; }
 public string ISBN { get; set; }
 public string Title { get; set; }
 public string Author { get; set; }
 public decimal Price { get; set; }
 public Address Address { get; set; }
 public Press Press { get; set; }
}

Creating Edm Model

OData uses EDM, Entity Data Model, to describe the structure of data. Add a create method to the Startup file.


private static IEdmModel GetEdmModel()
{
  var builder = new ODataConventionModelBuilder();
  builder.EntitySet<Book>("Books");
  builder.EntitySet<Press>("Presses");
  return builder.GetEdmModel();
}

Register OData Service

Register the OData service in the ConfigureServices method of the Startup file.


services.AddOData();
services.AddMvc(options =>
  {
    options.EnableEndpointRouting = false;
  }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

Note here that in. NET Core 2.2, the default has an endpoint, so to use the OData endpoint, you need to disable the default option.

Registration OData endpoint

Similarly, in Startup file, the original registered routing content is changed to the end point of registered OData in its Configure method.


app.UseMvc(b =>
{
  b.MapODataServiceRoute("odata", "odata", GetEdmModel());
});

Display metadata

After running the program, visit the https://localhost:5001/odata/$metadata address, and you can see the metadata of all available models.


<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
  <edmx:DataServices>
    <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="Default">
      <EntityType Name="Book">
        <Key>
          <PropertyRef Name="Id"/>
        </Key>
        <Property Name="Id" Type="Edm.Int32" Nullable="false"/>
        <Property Name="ISBN" Type="Edm.String"/>
        <Property Name="Title" Type="Edm.String"/>
        <Property Name="Author" Type="Edm.String"/>
        <Property Name="Price" Type="Edm.Decimal" Nullable="false"/>
        <Property Name="Address" Type="Default.Address"/>
        <NavigationProperty Name="Press" Type="Default.Press"/>
      </EntityType>
      <EntityType Name="Press">
        <Key>
          <PropertyRef Name="Id"/>
        </Key>
        <Property Name="Id" Type="Edm.Int32" Nullable="false"/>
        <Property Name="Name" Type="Edm.String"/>
        <Property Name="Email" Type="Edm.String"/>
        <Property Name="Category" Type="Default.Category" Nullable="false"/>
      </EntityType>
      <ComplexType Name="Address">
        <Property Name="City" Type="Edm.String"/>
        <Property Name="Street" Type="Edm.String"/>
      </ComplexType>
      <EnumType Name="Category">
        <Member Name="Book" Value="0"/>
        <Member Name="Magazine" Value="1"/>
        <Member Name="EBook" Value="2"/>
      </EnumType>
      <EntityContainer Name="Container">
        <EntitySet Name="Books" EntityType="Default.Book">
          <NavigationPropertyBinding Path="Press" Target="Presses"/>
        </EntitySet>
        <EntitySet Name="Presses" EntityType="Default.Press"/>
      </EntityContainer>
    </Schema>
  </edmx:DataServices>
</edmx:Edmx>

Create Controller

In this example, the operation of database is not considered, so hard code is used to construct the necessary model objects.


public class BooksController : ODataController
{
  private static IList<Book> Books {get; set;}
  public BooksController()
  {
    Books = new List<Book>
    {
      new Book
      {
        Id = 1,
        ISBN = "111-0-321-56789-1",
        Title = "Calculus",
        Price = 66.6m,
        Address = new Address
        {
          City = "Shanghai",
          Street = "Beijin Xi Road"
        },
        Press = new Press
        {
          Id = 1,
          Name = "Shanghai Tongji",
          Category = Category.Book
        }
      },
      new Book
      {
        Id = 2,
        ISBN = "222-2-654-00000-2",
        Title = "Linear Algebra",
        Price = 53.2m,
        Address = new Address
        {
          City = "Shanghai",
          Street = "Beijin Dong Road"
        },
        Press = new Press
        {
          Id = 2,
          Name = "Shanghai Fudan",
          Category = Category.EBook
        }
      }      
    };  
  }

  [EnableQuery]
  public IActionResult Get()
  {
    return Ok(Books);
  }

  [EnableQuery]
  public IActionResult Get(int key)
  {
    return Ok(Books.FirstOrDefault(b => b.Id == key));
  }
}

EnableQuery features must be added in scenarios where advanced queries are required.

query

After joining Controller, visit https://localhost:5001/odata/Books address to get all Book data.


{
  "@odata.context": "https://localhost:5001/odata/$metadata#Books",
  "value": [
    {
      "Id": 1,
      "ISBN": "111-0-321-56789-1",
      "Title": "Calculus",
      "Author": null,
      "Price": 66.6,
      "Address": {
        "City": "Shanghai",
        "Street": "Beijin Xi Road"
      }
    },
    {
      "Id": 2,
      "ISBN": "222-2-654-00000-2",
      "Title": "Linear Algebra",
      "Author": null,
      "Price": 53.2,
      "Address": {
        "City": "Shanghai",
        "Street": "Beijin Dong Road"
      }
    }
  ]
}

Access https://localhost:5001/odata/Books(1) address to get the Book data with a key value of 1.


{
  "@odata.context": "https://localhost:5001/odata/$metadata#Books/$entity",
  "Id": 1,
  "ISBN": "111-0-321-56789-1",
  "Title": "Calculus",
  "Author": null,
  "Price": 66.6,
  "Address": {
    "City": "Shanghai",
    "Street": "Beijin Xi Road"
  }
}

Advanced query

If you want to use the advanced functions of OData query, you can add the corresponding configuration when registering the endpoint.


app.UseMvc(b =>
{
  b.Select().Expand().Filter().OrderBy().MaxTop(100).Count();
  b.MapODataServiceRoute("odata", "odata", GetEdmModel());
});

When accessing the web site, add the required query contents:
https://localhost:5001/odata/Books?$select=Id,Title


{
  "@odata.context": "https://localhost:5001/odata/$metadata#Books(Id,Title)",
  "value": [
    {
      "Id": 1,
      "Title": "Calculus"
    },
    {
      "Id": 2,
      "Title": "Linear Algebra"
    }
  ]
}

It is also easy to filter data content according to specific conditions:
https://localhost:5001/odata/Books?$filter=Price%20le%2060


{
  "@odata.context": "https://localhost:5001/odata/$metadata#Books",
  "value": [
    {
      "Id": 2,
      "ISBN": "222-2-654-00000-2",
      "Title": "Linear Algebra",
      "Author": null,
      "Price": 53.2,
      "Address": {
        "City": "Shanghai",
        "Street": "Beijin Dong Road"
      }
    }
  ]
}

summary

It’s easy to see that the real appeal of OData is its support for those advanced query functions, so when creating RESTful APIs, consider using OData, which should reduce a lot of unnecessary code work.

Well, the above is the whole content of this article. I hope that the content of this article will have some reference and learning value for everyone’s study or work. If there is any doubt, you can leave a message to exchange. Thank you for your support for developpaer.