How to have Dynamic Queryable Entities in OData v4

2019-07-12 01:50发布

问题:

In the task of building a web api using OData v4, entity and C#, I got stuck in the following problem. I have a view in my DB (SQL Server) that has some yearly info as rows, such as...

    |Year |Value |
     1985  8.7
     1986  8.8

But I need to serve them as columns:

    |1985 |1986 |
     8.7    8.8

The years are dynamic, I couldn't find a way to create a model class that is dynamic. Because of that, I couldn't find a way to serve the data in the controller. I was able to pivot the information using C# code, but OData doesn't serve it, because there was no corresponding model.

I tried to use a library called MedallionOdata, it has a ODataEntity that was supposed to be dynamic and Queryable, but I couldn't make it work.

What is the best way to serve dynamic entities keeping the queryable aspects of OData?

回答1:

OData has a concept of "open types" that I think will help you to achieve what you are looking for. They essentially let you add any properties onto an object.

If you are using the ODataConventionModelBuilder, it is as simple as adding a property of type IDictionary<string, object> to your model class like this:

public IDictionary<string, object> Properties { get; set; }

You can find more details here: https://docs.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/use-open-types-in-odata-v4