2

I trying to understand how to return a group by result in web.api interface, like so...

[ActionName("Archive")]
public HttpResponseMessage GetArchiveImport() {
    try {
        var result = _service.QueryFor(x => x.ActionType == ActionType.Import)
            .GroupBy(x => x.InsertDate,
                (key, group) => new {
                    Date = key,
                    Entries = group.ToList()
                }).ToList();

        return Request.CreateResponse(HttpStatusCode.OK, result);
    }
    catch (Exception e) {
        _logger.Error("Failed to retrive import file", e);
    }
    return Request.CreateResponse(HttpStatusCode.InternalServerError);
}

The QueryFor returns => IEnumerable<History>

I'm not getting any results, can some one explain why?

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
hackp0int
  • 4,052
  • 8
  • 59
  • 95

1 Answers1

1

Why not just simplify to this

var result = _service.QueryFor(x => x.ActionType == ActionType.Import)
            .GroupBy(x => x.InsertDate);

and check the result with your debug'er. If you don't get any data, then it is your QueryFor that doesn't return any.

Is your question really along these lines Is there a way to force ASP.NET Web API to return plain text?

You have the data in your result, but doesn't get them over the wire as expected?

If this i supposed to be a normal Web API method your method signature should be like

public IEnumerable<IGrouping<DateTime, History>> GetArchiveImport()

Ok - getting closer :) Web API doesn't know about IGrouping - I guess you can register this somehow.

A quick fix will be to create your own Grouping class, like

public class HistoryGroup
{
   public DateTime InsertDate { get; set; }
   public IEnumerable<History> History { get; set; }
}

then change your group by to

var result = _service.QueryFor(x => x.ActionType == ActionType.Import)
            .GroupBy(x => x.InsertDate,
                (key, group) => new HistoryGroup() {
                    InsertDate = key,
                    History = group
                })

and return result.ToList()

the return value for your function would be IEnumerable<HistoryGroup>

Community
  • 1
  • 1
Frode Nilsen
  • 167
  • 2
  • 11
  • Care to comment why this got downvoted, I for one doesn't get the value of (key, group) => new { Date = key, Entries = group.ToList() } – Frode Nilsen Feb 03 '14 at 07:38
  • I would like to return the exact result as I've showed, not an other signatures and the same exact grouped data. – hackp0int Feb 03 '14 at 08:34
  • Ok - then you will have to serialize this to xml/json/whatever-you-like yourself. With the signature above you would just do return result.ToList() – Frode Nilsen Feb 03 '14 at 09:59
  • Here http://stackoverflow.com/a/8508212/2294065 you find more info about the IGrouping problem – Frode Nilsen Feb 03 '14 at 12:02