How to enable $levels in oData .Net core 3.1

Viewed 481

I have developed an oData server with .Net core 3.1.

Asp.net in its older versions support $levels for example check here.

In my server I can expand my queries until 2 levels. It means a URL like the following:

https://localhost:44375/odata.svc/Patients?$expand=PatientForms($expand=Form)

works in my server and I can see the expanded results. Now if I try to perform it with $levels:

https://localhost:44375/odata.svc/Patients?$expand=PatientForms($levels=2)

then I will get the following error:

The query specified in the URI is not valid. The $level option on navigation property 'PatientForms' is not allowed, because the related entity type 'mjzsoft.Models.PatientForm' could not be cast to source entity type 'mjzsoft.Models.Patient'.

The controllers for Patient and PatientForm and Form are as follows, however as they have exactly same structure with different model names, therefore, I just reflected one of them here:

[ODataRoutePrefix("Patients")]
    public class PatientsController : ODataController
    {
        private readonly XxxDbContext xxxDbContext;
        public PatientsController(XxxDbContext xxxDbContext)
                => this.xxxDbContext = xxxDbContext;
        
        [ODataRoute]
        [EnableQuery]
        //[PagingValidatorQuery]
        public IActionResult Get()
        {
            return Ok(this.xxxDbContext.Patients);
        }

        [ODataRoute("{id}")]
        [EnableQuery]
        public IActionResult Get([FromODataUri] ulong id)
        {
            return Ok(this.xxxDbContext.Patients.FirstOrDefault(item => item.Id == id));
        }

    }

In the database each Patient can have several Form. Hence, as this is an M to N relationship we have PatientForms in between.

1 Answers

The query specified in the URI is not valid. The $level option on navigation property 'PatientForms' is not allowed, because the related entity type 'mjzsoft.Models.PatientForm' could not be cast to source entity type 'mjzsoft.Models.Patient'.

I met this problem with your codes. From the link you post, it said $levels only used to expand same object.

$expand=Manager($levels=max) will be the same as $expand=Manager($expand=Manager)   
$expand=Manager($levels=3) will be the same as $expand=Manager($expand=Manager($expand=Manager))

As for your case, you need $expand=PatientForms($expand=Paitent)
$expand=PatientForms($levels=2) will expect to expand PatientForms but Paitent and the cast error showed up.

Here are test results of using $levels below.

Comments => $expand once

enter image description here

Comments => $expand twice is same as Comments => $levels=2

enter image description here

enter image description here

Related