【发布时间】:2017-06-15 23:09:32
【问题描述】:
(抱歉标题含糊,不知道该怎么写。)
这是 .NET 4.7、EF 6.1。我有两张表:一组产品和一组历史价格。我需要编写一些代码来获取截至两个提供日期(开始和结束)的所有产品及其价格的列表。这本质上是一份报告,用于查看产品价格在两个日期之间的变化情况,但我只需要开始/结束价格,而不是中间的所有价格。
我能想到的唯一方法是类似于下面的代码。我会运行两次——一次用于开始日期,一次用于结束日期——然后我会将这两个列表加入到我需要的模型类型列表中。我无法为我的生活弄清楚如何做到这一点。 我应该如何做到这一点?
简化的表格布局:
Product HistoricalPrice
------- ---------------
-Id -Id
-Name -ProductId
-ModifiedAt
-NewPrice
这是我尝试使用的代码。 Product 是对HistoricalPrice 的Product 的引用,它是类的一部分,并由ProductId 字段引用。我需要从此代码的最终结果中获取产品名称/ID。
var historicalStartPrices = await _context.ProductHistoricalPrices
// need to include the product itself
.Include(p => p.Product)
// only get prices that come before the start date
.Where(p => p.ModifiedAt <= start)
// order from most recent -> oldest by modified date
.OrderByDescending(p => p.ModifiedAt)
// group prices by the product ID
.GroupBy(p => p.ProductId)
// take only the first result for each product ID
.Select(g => g.First())
// enumerate the results
.ToListAsync();
该代码抛出此异常:
NotSupportedException:方法“First”只能用作最终查询操作。请考虑在此实例中使用“FirstOrDefault”方法。
如果我切换到FirstOrDefault,那么所有Products 都是空的。
【问题讨论】:
标签: c# .net entity-framework