Search code examples
c#entity-frameworkodata

Return a list of entities with OData & Entity Framework


I have an OData method and I want to return a List of entities from that method.

This is my code

public async Task<IHttpActionResult> LoadSpecimenMachinings([FromODataUri] Int32 key)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    Int32 stage = 1;
    string csvSpecimenCodes = "S0,S1,S2";

    List<Machining> machinings = null;
    var machiningResult = db.LoadSpecimenMachinings(key, stage, csvSpecimenCodes);
    machinings = (from machining in machiningResult select machining).ToList();

    return Created(machinings);
}

When I returned a List of entities (Machining is an entity in my Entity Framework Model) in the line return Created(machinings); I received the following error:

"message":" is not an entity type. Only entity types are supported.",
"type":"System.InvalidOperationException"

As I understand, unfortunately Created cannot receive a List of Entities as parameter. Is there any way to return a list of entities and a Created HTTP Code in OData ?

I am using OData V3 and Entity Framework 6.


Solution

  • return Created() is designed to only return a single element and for use when you do an insert, this returns a 201 Created status code

    You should use return Ok(machinings) this returns a 200 OK status code

    See the OData specification on response code http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398250