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

走远了吗. 提交于 2019-12-13 06:26:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!