Alternate key in WebApi
Applies To:# OData WebApi v7 for aspnet webapi supported OData AspNet WebApi V7# OData Webapi for Webapi supported OData AspNet WebApi V6
Alternate keys is supported in Web API OData V5.7. For detail information about alternate keys, please refer to here
The related sample codes can be found here
Users can enable alternate key in the global configuration.
HttpConfiguration config = ...
config.EnableAlternateKeys(true);
config.MapODataServiceRoute(...)
So far, an Edm model with alternate keys can be built by ODL APIs.
EdmEntityType customer = new EdmEntityType("NS", "Customer");
customer.AddKeys(customer.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
customer.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
var ssn = customer.AddStructuralProperty("SSN", EdmPrimitiveTypeKind.String);
model.AddAlternateKeyAnnotation(customer, new Dictionary<string, IEdmProperty>
{
{"SSN", ssn}
});
model.AddElement(customer);
So, SSN is an alternate key.
In OData controller, Users can use the attribute routing to route the alternate key. The Uri template is similar to function parameter. For example:
[HttpGet]
[ODataRoute("Customers(SSN={ssn})")]
public IHttpActionResult GetCustomerBySSN([FromODataUri]string ssn)
{
...
}