Antoine V
Antoine V

Reputation: 7204

How to expand navigation properties on POST/PUT OData request

I'm using OData ASP.NET Core 7.4.1

For exemple, with a request GET https://localhost:44346/api/v1/estates/74EEAB44-B8E7-EA11-B361-D43B04C15376?$expand=tenants , I can get a entity with the info of tenants

{
    "@odata.context": "https://localhost:44346/odata/v1/$metadata#Estates(tenants(),tenants())",
    "value": [
        {            
            "updatedOn": "2020-08-26T16:22:01.03+02:00",
            "tenants": [
                {
                    "name": "tenant"
                }
            ]
        }
    ]
}

But with Put request PUT https://localhost:44346/odata/v1/estates(74EEAB44-B8E7-EA11-B361-D43B04C15376)?$expand=tenants , I can get my returned entity but without tenants

{
    "@odata.context": "https://localhost:44346/odata/v1/$metadata#Estates(tenants(),tenants())",
    "value": [
        {            
            "updatedOn": "2020-08-26T16:22:01.03+02:00",
            "tenants": []
        }
    ]
}

Question : How to return tenants of returned entity in PUT request, because I don't want to have to make a GET(id) call to the server to refresh a created/updated entity. The server should return exactly the same representation of the entity as the GET(id).

There is a ticket opened about this but not resolve. Someone has solved this problem ?

Upvotes: 3

Views: 905

Answers (1)

Michael Wang
Michael Wang

Reputation: 4022

Here is the setting in Startup.cs

        app.UseMvc(routeBuilder =>
        {
            routeBuilder.EnableDependencyInjection();
            routeBuilder.Select().Expand().Filter().OrderBy().MaxTop(10).Count();

            var builder = new ODataConventionModelBuilder(app.ApplicationServices);
            builder.EntitySet<Tenants>("estates");
            routeBuilder.MapODataServiceRoute("ODataRoute", "odata/v1", builder.GetEdmModel());
        });

Codes of Modes

public class Tenants
{
    public int id { get; set; }
    public DateTime updatedOn { get; set; }
    public List<Tenant> tenants { get; set; }
}

public class Tenant
{
    public string name { get; set; }
}

HTTP GET

    [HttpGet]
    [EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
    public async Task<IActionResult> Get()
    {
        var tenants = (await dataProvider.GetTenants()).ToList();
        return Ok(tenants);
    }

enter image description here

HTTP PUT

    [HttpPut("{key}")]
    [ODataRoute("{key}")]
    [EnableQuery]
    public async Task<IActionResult> ([FromODataUri] Guid key, [FromBody] Estate estate)
    {
        var tenants = (await dataProvider.SetTenants(name)).ToList();
        return Ok(tenants);
    }

enter image description here

Upvotes: 2

Related Questions