LINQ:一起添加/汇总集合中的所有时间跨度

时间:2015-09-14 17:08:53

标签: c# linq timespan

我正在尝试简单地在我的ViewModel中添加所有TimeSpans,但是我一直收到错误(我可以向你保证'x.totalDuration'实际上是一个TimeSpan并且'myCollection'确实是一个IEnumerable:

查看:

  var myCollection = Model.Select(x => x.totalDuration);
  var ts = new TimeSpan(myCollection.Sum(r => r.Ticks)); <-- boom here--<

控制器:

 [HttpGet]
    public ActionResult List()
    {
        var model = _db.Tracks
          .Where(r => r.UserID == WebSecurity.CurrentUserId)
          .Select(x => new iOSHistoryListViewModel
          {
              averagePace = Math.Round(26.8224 / x.locations.Average(y => y.speed), 2),
              createdDate = x.createdDate,
              FirstName = x.UserProfile.FirstName,
              totalDistance = Math.Round(x.totalDistance / 1609.344, 2),
              totalDuration = TimeSpan.FromSeconds(x.totalDuration),
              trackId = x.TrackID
          })
          .OrderByDescending(x => x.createdDate)
          .ToList(); <-- tried with/without this

        return View(model);
    }

错误:

LINQ to Entities does not recognize the method 'System.TimeSpan FromSeconds(Double)' method, and this method cannot be translated into a store expression.

Description: An unhandled exception occurred during the execution of the     current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NotSupportedException: LINQ to Entities does not recognize the method 'System.TimeSpan FromSeconds(Double)' method, and this method cannot be translated into a store expression.

Source Error: 


Line 13:         @{
Line 14:             var myCollection = Model.Select(x => x.totalDuration);
Line 15:             var ts = new TimeSpan(myCollection.Sum(r => r.Ticks));

这很简单,但我遗漏了一些东西......

1 个答案:

答案 0 :(得分:1)

问题是你试图在数据库中调用TimeSpan.FromSeconds。这是一种.NET方法,无法翻译。这是未经测试的,但为了解决这个问题:

        var model = _db.Tracks
      .Where(r => r.UserID == WebSecurity.CurrentUserId)
      .Select(x => new
      {
          averagePace = Math.Round(26.8224 / x.locations.Average(y => y.speed), 2),
          createdDate = x.createdDate,
          FirstName = x.UserProfile.FirstName,
          totalDistance = x.totalDistance,
          totalDuration = x.totalDuration,
          trackId = x.TrackID
      }).ToList()
      .Select(x => new iOSHistoryListViewModel{
          averagePace = x.averagePace,
          createdDate = x.createdDate,
          FirstName = x.FirstName,
          totalDistance = Math.Round(x.totalDistance / 1609.344, 2),
          totalDuration = TimeSpan.FromSeconds(x.totalDuration),
          trackId = x.trackId
      })
      .OrderByDescending(x => x.createdDate)
      .ToList();

这里的关键是第一个Select将从数据源返回的数据抛出到列表中。然后列表在.NET内存中,您可以在其中执行任何.NET操作。然后将该结果集发送到新列表。这应该摆脱你的例外.FromSeconds