Type inheritance is not frequently implemented in OData services. I’d say that REST services is not a very good fit for OO paradigm and there are other means to expose information in a REST service than to open up the whole object hierarchy. However, today the easiest way to build an OData service is to write a tiny wrapper around Entity Framework model using WCF Data Services. So if OData didn’t have support for inheritance, it would leave out a wide range of real-world data models. Therefore OData and WCF Data Services has full support for type inheritance, and so do the Simple.Data OData adapter. Initially inheritance was added in the version 0.11 at request from Gianni Mellon (thanks for a valuable feedback), and the version 0.12 fixed a few bugs related to update and deletion of inherited type instances.
Consider the following type hierarchy:
“Transport” is an abstract type, and we want to be able to retrieve and modify both derived types: “Ships” and “Trucks”. Here’s how you can do it with Simple.Data and its OData adapter.
1. Retrieving all transport instances (both ships and trucks)
IEnumerable<dynamic> transports = _db.Transport.All();
Then you can traverse the resulting collection and access either ShipName or TruckNumber properties depending on the concrete type of each element.
2. Retrieving only derived type (ships) instances
IEnumerable<dynamic> ships = _db.Ships.All();
Simple, isn’t? It’s Simple.Data. Now let’s look up just one ship:
var ship = _db.Ships.Find(_db.Ships.ShipName == "Titanic");
3. Creating new entries
var ship = _db.Ships.Insert(ShipName: "Test1");
4. Updating entries
_db.Ships.UpdateByTransportID(TransportID: ship.TransportID, ShipName: "Test2");
var ship = _db.Ships.Find(_db.Ships.ShipName == "Titanic"); ship.ShipName = "Not Titanic"; _db.Ships.Update(ship);
5. Deleting entries
var ship = _db.Ships.Find(_db.Ships.ShipName == "Titanic"); _db.Ships.Delete(ship);
The latest Simple.Data.OData package is available from NuGet.