Pergunta

I have web api odata service that I need to return some data that was generated from a LINQ query that flattens an entity. For example I have a list of orders that I have used LINQ on the data service side to generate new properties such that I would like to return the number of orders that have a count between 0 and 100 then another property that would have a count between 101 and 200. etc. Here is a simplified example.

Public IHttpActionResult GetCustomData()
{
    var query = (from o in Orders
            select CustomerName = o.CustomerName,
            LowerCount = o.OrderDetails.Where(f => f.Pieces >= 0 && f.Pieces <= 100).Count(),
            MidCount = o.OrderDetails.Where(f => f.Pieces >= 101 && f.Pieces <= 200).Count(),
            HighCount = o.OrderDetails.Where(f => f.Pieces >= 201).Count()
            );

    return Ok(query);
}

In my WebApiConfig I the FunctionConfiguration with code like following:

FunctionConfiguration getCustomData = builder.EntityType<Order>().Collection.Function("GetCustomData");
getCustomData.Returns<Object>();

The url lets me call the function correctly but the json returned contains empty arrays. For example: if there are 6 records to return then the Json will have 6 empty [] inside.

I also tried to return Newtonsoft.Json.Linq.JObject and used Newtonsoft to serialize the LINQ into Json but then I get a runtime error.
"The complex type 'JToken' has a reference to itself through the property 'Parent'. A recursive loop of complex types is not allowed."

I know I could create custom classes to fix this problem but there has to be some easier way to send generic Json to the client so that the client can unwrap and read the data.
I also know that I could send the entire order / order details to the client so that the client could "count" the data but I want to leave the payload small coming from the web service.
I feel that I am close since the client is getting back a json array but the array is empty.

Foi útil?

Solução

You can use string as the return type.

Public IHttpActionResult GetCustomData()
{
    var query = (from o in Orders
            select CustomerName = o.CustomerName,
            LowerCount = o.OrderDetails.Where(f => f.Pieces >= 0 && f.Pieces <= 100).Count(),
            MidCount = o.OrderDetails.Where(f => f.Pieces >= 101 && f.Pieces <= 200).Count(),
            HighCount = o.OrderDetails.Where(f => f.Pieces >= 201).Count()
            );

    return Ok(JsonConvert.SerializeObject(query));
}

FunctionConfiguration:

FunctionConfiguration getCustomData = builder.EntityType<Order>().Collection.Function("GetCustomData");
getCustomData.Returns<string>();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top