【发布时间】:2011-07-18 14:00:44
【问题描述】:
我有一个这样定义的扩展方法:
public static TSource MaxBy<TSource, TResult>(this IEnumerable<TSource> collection, Func<TSource, TResult> func) where TSource : class
{
var comparer = Comparer<TSource>.Default;
TSource maxItem = null;
foreach (var item in collection)
{
if (comparer.Compare(item, maxItem) > 0)
maxItem = item;
}
return maxItem;
}
然后我在以下 LINQ-to-Entities 查询中使用它:
var balancesQuery = from t in db.Transactions
where t.UserId == userId
group t by t.CurrencyCode into tg
let tMaxDate = tg.MaxBy(i => i.TsCreate)
join c in db.Currencies on tg.Key equals c.CurrencyCode
select new { Currency = c, Balance = tMaxDate.Balance }
所以我要做的是 - 获取每种货币(按 CurrencyCode 分组)的最新交易 (MaxBy TsCreate),然后针对每笔交易选择余额。
我的问题是 - 这不适用于实体框架(LINQ-to-Entities;我得到:
LINQ to Entities 无法识别方法 'Transaction MaxBy[Transaction,DateTime](System.Collections.Generic.IEnumerable'[Transaction], System.Func'2[Transaction,System.DateTime])' 方法,并且这个方法不能翻译成商店表达式。
同样的查询也适用于 LINQ to SQL。
我的问题是:
- 有没有办法让它与实体框架一起工作?
- 或者也许有更好的方法来查询相同的信息,这适用于实体框架?
提前感谢您的帮助!
【问题讨论】:
标签: entity-framework linq-to-sql linq-to-entities