문제

I'm working on a project which implements ASP.NET Web API OData controllers. I'm trying to create a custom queryable GET action on an entity, however after extensive search, I have not found a straightforward way of doing so.

I have an Inventory model with a Snapshot property, in turn having an Entries collection (inventory.Snapshot.Entries). The logical relationships are: inventory uses snapshot, snapshot contains entries. Only some of the entries of the snapshot are relevant to the inventory, according to other properties of the inventory. On top of that, the inventory may not have a specific snapshot defined, in which case its Snapshot property is null and a suitable snapshot must be sought.

That said, I would like the following URL to be valid, even though Inventory does not have an Entries property:

/odata/Inventories(1)/Entries

And under InventoriesController:

public async Task<IQueryable<Entry>> GetEntries([FromODataUri] int key)
{
    var inventory = await db.Inventories.FindAsync(key);
    if (inventory.SnapshotId != null)
    {
         return QueryRelatedEntriesInSnapshot(inventory, inventory.SnapshotId);
    }
    else
    {
         return QueryRelatedEntriesInSnapshot(inventory, await GetBestSnapshot(inventory, db.Snapshots));
    }
}

Does this require a custom routing convention or can I register fake navigation properties in the ODataConventionModelBuilder so that it generates the routes? Or any other solution?

Thanks for any help

도움이 되었습니까?

해결책

You don't have to create a fake navigation property. What you need to do are:

  1. Add a complex type:

    oDataConventionModelBuilder.ComplexType<Entry>();
    
  2. Add a property in Inventory:

    public class Inventory
    {
        public IList<Entry> Entries { get; set; }
        // Other properties.
    }
    
  3. Add the property in Entity Type Inventory in EDM model.

That's it.

Note if your controller name is InventoriesController, you need to access entries in this URL '/odata/Inventories(1)/Entries' instead of '/odata/Inventory(1)/Entries'

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top