OData with multiple keys
I am using the Microsoft.OData 6.11.0 package and I would like API users to be able to use one of three properties (DB primary key, username, or external ID) as a key for the data type representing people. The formats for properties vary so much that they can be easily distinguished. I have set up OData model like this:
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Person>("Person");
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: "OData",
model: builder.GetEdmModel());
In the controller I have:
[EnableQuery]
public SingleResult<Person> Get([FromODataUri] String key) {/*...*/}
[EnableQuery(PageSize = 100)]
public IQueryable<Widget> WidgetsFromPerson([FromODataUri] String key) {/*...*/}
which takes a guess where the id is given and returns the data accordingly. These works:
GET http://localhost/app/OData/Person(1234)
GET http://localhost/app/OData/Person(999999999)
GET http://localhost/app/OData/Person(1234)/Widgets
GET http://localhost/app/OData/Person(999999999)/Widgets
They get me a 404.
GET http://localhost/app/OData/Person('username')
GET http://localhost/app/OData/Person('username')/Widgets
If I cannot do this, is there an alternative syntax I can use to get the username by username, and also widgets for that person by username?
Metadata returned through the API includes the following:
<edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx">
<edmx:DataServices>
<Schema Namespace="MyModel" xmlns="http://docs.oasis-open.org/odata/ns/edm">
<EntityType Name="AbstractPerson" Abstract="true">
<Key>
<PropertyRef Name="PersonId" />
</Key>
<Property Name="PersonId" Type="Edm.Int32" Nullable="false" />
</EntityType>
<EntityType Name="Person" BaseType="MyModel.Person">
<Property Name="UserName" Type="Edm.String" />
<NavigationProperty Name="Widgets" Type="Collection(MyModel.Widget)" />
</EntityType>
</Schema>
</edmx:DataServices>
</edmx:Edmx>
Thank!
source to share
I really think you are looking for a function similar to the alternate key.
The OData team is working on supporting alternate keys. You can find details and sample from here
Alternatively, you can find an implementation .
source to share