问题
I have code below:
void Main()
{
var q = from a in Applicants
where(a.Claims.Any())
select a.Claims.Sum(c => c.TotalClaimAmount());
q.Dump();
}
public static class MyExt
{
public static decimal TotalClaimAmount(this Claim c)
{
var t = c.Accommodations.Sum(a => a.AmountClaimed) +
c.MealAllowances.Sum(ma => ma.AmountClaimed) +
c.Meals.Sum(m => m.AmountClaimed) +
c.Mileages.Sum(mi => mi.AmountClaimed) +
c.Others.Sum(o => o.AmountClaimed) +
c.ParkingTransits.Sum(pt => pt.AmountClaimed) +
c.Travels.Sum(tr => tr.AmountClaimed);
return (decimal)t;
}
}
when I run it in LinqPad get below issue:
InvalidOperationException: Could not translate expression 'a.Claims.Sum(c => c.TotalClaimAmount())' into SQL and could not treat it as a local expression.
Please help me out. Many thanks
回答1:
There is no corresponding command for your custom method in SQL. so compiler could not translate your expression. Instead first get your items,then select your results:
var items = Applicants.Where(a => a.Claims.Any()).ToList();
var results = items.Select(a => a.Claims.Sum(c => c.TotalClaimAmount());
回答2:
LINQ is unable to convert the TotalClaimAmount
method call to a SQL expression.
What you can do, is to extract the expression from the TotalClaimAmount
method and use it directly in the Sum
method call.
public static class MyExt {
public static Func<Claim, decimal> TotalClaimAmountFunc = c =>
c.Accommodations.Sum(a => a.AmountClaimed) +
c.MealAllowances.Sum(ma => ma.AmountClaimed) +
c.Meals.Sum(m => m.AmountClaimed) +
c.Mileages.Sum(mi => mi.AmountClaimed) +
c.Others.Sum(o => o.AmountClaimed) +
c.ParkingTransits.Sum(pt => pt.AmountClaimed) +
c.Travels.Sum(tr => tr.AmountClaimed);
public static decimal TotalClaimAmount(this Claim c) {
return TotalClaimAmountFunc(c);
}
}
void Main() {
var q = from a in Applicants
where(a.Claims.Any())
select a.Claims.Sum(MyExt.TotalClaimAmountFunc);
q.Dump();
}
来源:https://stackoverflow.com/questions/21590215/how-to-solve-issue-could-not-translate-expression-into-sql-and-could-not-tre