How to solve issue "Could not translate expression ...into SQL and could not treat it as a local expression." [duplicate]

StackOverflow https://stackoverflow.com/questions/21590215

Question

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

Was it helpful?

Solution 2

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());

OTHER TIPS

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top