Entity
A WebService entity can have multiple keys to be uniquely identified.
namespace UserServices
{
[DataServiceKey("Name")]
[DataServiceEntity]
public class Person
{
public string Name {get; set;}
}
}
Example:
Get Person with Key: http://localhost:8080/sap/opu/odata/Test/TEST_SRV/Persons(‘Angela’)
Supported Types
All primitive types are supported, click to see them. System.Object is NOT supported.
Navigation Properties
A navigation property can easily be created by adding an other entity as property to your entity.
Example:
Let’s create a new entity class Countries, with a NavigationProperty called President. President is of type Person.
namespace UserServices
{
[DataServiceKey("Name")]
[DataServiceEntity]
public class Country
{
public string Name {get; set;}
public Person President {get; set;}
}
}
The ServiceMethod of the main entity has to handle reading, adding, updating and deleting the navigation properties.
Therefore the Query function has to always return fully setup Entities including their NavigationProperties.
public class Countries : ServiceMethod<Country>
{
public override IEnumerable<Country> Query(IExpression<Country> expression)
{
return new[]
{
new Country { Name = "Germany",
President = new Person { FirstName = "Angela", LastName = "Merkel", Address = "Platz der Republik 1 - 11011 Berlin", Age = 60 }
},
new Country { Name = "USA",
President = new Person { FirstName = "Barack", LastName = "Obama", Address = "The White House - 1600 Pennsylvania Avenue NW Washington, DC 20500", Age = 53 }
},
new Country { Name = "Russia",
President = new Person { FirstName = "Vladimir", LastName = "Putin", Address = "Russia", Age = 62 }
}
}
}
}
Request and response:
GET http://localhost:8080/Test/MyFirstWebService/Countries('Germany')/President?$format=json
{
"d": {
"FirstName": "Angela",
"LastName": "Merkel",
"Age" : 60,
"Address": "Platz der Repluk 1 - 11011 Berlin"
}
}
Collections
When working with NavigationProperty as collections, IEnumerable should be used as the property type.
Collections need to be set to a default empty value in the constructor of the entity.
[DataServiceKey("Name")]
[DataServiceEntity]
public class Organisation
{
public string Name {get; set;}
public IEnumerable<Person> Employees {get; set;}
public Organisation()
{
Employees = new List<Person>();
}
}
Note
To add, remove or update an employee in your Organisation you have to use the ServiceMethod of the Employee instead of the Organisation.
Therefore you always have to create a ServiceMethod for the NavigationProperty type when working with Collections.
Example:
Creating an entity with all it’s nested NavigationProperties in a single POST request:
Request for creating an Organisation with all it’s employees:
POST http://localhost:8080/Test/MyFirstWebService/Organisations
Accept: application/json
{
"Employees": [
{
"FirstName": "Martin",
"LastName": "Weiss",
"Age" : 22
},
{
"FirstName": "Manuel",
"LastName": "Lanthaler",
"Age" : 16
}
]
}