OData on .Net Core doesn't return the right results on $select
I had the same problem. This solved the problem for me. Perhaps odata is not fully compatible with the new JSON serializer in Asp.Net 3.1. I don't know.
services.AddControllers(mvcOptions =>
mvcOptions.EnableEndpointRouting = false)
.AddNewtonsoftJson();
The APIs are working fine, but when I try to add some OData action like $select I get the following and not the expected results
I can reproduce the same issue in my .NET Core 3.x
application with similar code as you shared, it seems that currently injecting OData services into existing API controller with the following code snippet does not support well for .NET Core 3.x.
routeBuilder.EnableDependencyInjection();
And based on my test, it can work well in .NET Core 2.x
. To make $select
functionality work fine in .NET Core 3.x
, currently, we can try this workaround:
In Startup.cs
var builder = new ODataConventionModelBuilder(app.ApplicationServices);
builder.EntitySet<Product>("Products");
app.UseMvc(routeBuilder =>
{
// and this line to enable OData query option, for example $filter
routeBuilder.Expand().Select().OrderBy().Filter();
routeBuilder.MapODataServiceRoute("ODataRoute", "api", builder.GetEdmModel());
});
In ODataController
public class ProductsController : ODataController
{
// ...
//code logic here
// ...
[HttpGet]
[EnableQuery]
public IQueryable<Product> Get()
{
var products = _context.Products;
return products;
}
// ...
}
Test Result
For more information, please check: https://docs.microsoft.com/en-us/odata/webapi/netcore#e-configure-the-odata-endpoint