【发布时间】:2014-10-14 19:33:00
【问题描述】:
decimal tmpPreviousSellingRate = db.DataServiceCurrenciesRates
.Where(x => x.CurrencyId == tmpCurrencyId)
.OrderByDescending(x => x.PublicationDate)
.Select(x => x.SellingRate)
.DefaultIfEmpty()
.First();
在数据库中我有:
CurrencyId: 1 PublicationDate: '2014-08-19' SellingRate: 3,4530
CurrencyId: 2 PublicationDate: '2014-08-19' SellingRate: 0,6117
CurrencyId: 3 PublicationDate: '2014-08-19' SellingRate: 1,3570
CurrencyId: 1 PublicationDate: '2014-08-20' SellingRate: 3,3753
CurrencyId: 2 PublicationDate: '2014-08-20' SellingRate: 0,5442
CurrencyId: 3 PublicationDate: '2014-08-20' SellingRate: 1,5478
CurrencyId: 1 PublicationDate: '2014-08-21' SellingRate: 3,38263
CurrencyId: 2 PublicationDate: '2014-08-21' SellingRate: 0,5837
CurrencyId: 3 PublicationDate: '2014-08-21' SellingRate: 1,4635
当 CurrentId 为 2 时,我想得到 0,5837,但在 tmpPreviousSellingRate 中是 0,6117(从 2014-08-19 开始)
我使用了 OrderByDescending 和 OrderBy - 结果是一样的,都是 0,6117。
使用 .Last() 而不是 .First() 我得到一个错误
"Additional information: LINQ to Entities does not recognize the method 'System.Decimal Last[Decimal](System.Linq.IQueryable`1[System.Decimal])' method, and this method cannot be translated into a store expression."
【问题讨论】:
-
PublicationDate列的数据类型是什么? -
您是否检查了 Where 子句是否返回了与 CurrencyId == 2 相关的三个条目?尝试删除 DefaultIfEmpty() 和 First(),您应该检索有序列表。
-
PublicationDate是date。不,我没有检查我现在就做。 -
是的,在
Where中都是三个条目。 -
Last()can't be mapped to a Sql query。如果Where谓词之后的数据量很小,您可以在应用链的其余部分之前使用.ToList()实现数据。此外,您应该能够用单个FirstOrDefault()替换最后两个函数
标签: c# linq entity-framework linq-to-entities