Search code examples
c#asp.net-coreodata

ASP.NET Core 5.0 OData $select not working


In my ASP.NET Core 5.0 REST API I am using Microsoft.AspNetCore.OData v.7.5.2 and Entity Framework v.5.0.2

I have a Controller that implements ODataController and a SearchContacts function.

[HttpGet]
[EnableQuery(PageSize = 50)]
[Route("[action]")]
public ActionResult<IQueryable<ContactModel>> SearchContacts()
{
    return this.Ok(this._context.Contacts.AsQueryable());
}

For SearchContacts I can use $filter, $top and $skip just fine. When I try to use $select I get a strange result:

[
{
    "instance": null,
    "container": {},
    "modelID": "f4ca8855-11fa-4822-8f11-dc39b3c3c3f8",
    "untypedInstance": null,
    "instanceType": null,
    "useInstanceForProperties": false
},
{
    "instance": null,
    "container": {},
    "modelID": "f4ca8855-11fa-4822-8f11-dc39b3c3c3f8",
    "untypedInstance": null,
    "instanceType": null,
    "useInstanceForProperties": false
}
]

I tried updating Microsoft.AspNetCore.OData to version 7.5.4 but then I get an error: Severity Code Description Project File Line Suppression State

Error CS1705 Assembly 'Microsoft.AspNetCore.OData' with identity 'Microsoft.AspNetCore.OData, Version=7.5.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' uses 'Microsoft.OData.Edm, Version=7.7.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' which has a higher version than referenced assembly 'Microsoft.OData.Edm' with identity 'Microsoft.OData.Edm, Version=7.7.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'


Solution

  • //in program.cs add

    builder.Services.AddControllers()
    .AddOData(opt => opt.AddRouteComponents("odata", GetEdmModel())
    .Select()
    .Filter()
    .OrderBy()
    .SetMaxTop(null)
    .Count()
    .Expand()
     );
    
    
      Microsoft.OData.Edm.IEdmModel GetEdmModel()
      {
         ODataConventionModelBuilder builder = new 
         ODataConventionModelBuilder();
         builder.EntitySet<ProductEntity>("Product/GetAllQ");
         return builder.GetEdmModel();
      }