如何返回“分组”汇总结果?

时间:2014-02-03 06:13:13

标签: c# linq asp.net-mvc-4 asp.net-web-api

我试图了解如何通过web.api界面中的结果返回组,就像这样......

[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);
}

QueryFor返回=&gt;的 IEnumerable<History>

我没有得到任何结果,有人可以解释原因吗?

1 个答案:

答案 0 :(得分:1)

为什么不简化这个

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

并使用您的调试器检查结果。如果您没有获得任何数据,那么您的QueryFor不会返回任何数据。

你的问题是否真的沿着这些方向Is there a way to force ASP.NET Web API to return plain text?

您的结果中有数据,但是没有按预期通过网络获取数据?

如果我认为这是一个普通的Web API方法,那么您的方法签名应该是

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

好的 - 越来越近了:) Web API不知道IGrouping - 我猜你可以用某种方式注册。

快速解决方法是创建自己的分组类,例如

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

然后将您的论坛更改为

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

并返回result.ToList()

您的函数的返回值为IEnumerable<HistoryGroup>

相关问题