如何解决问题“无法将表达式转换为SQL并且无法将其视为本地表达式”。

时间:2014-02-05 22:44:56

标签: c# linq linq-to-sql linq-to-entities linqpad

我的代码如下:

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;
    }
}

当我在LinqPad中运行时遇到以下问题:

InvalidOperationException:无法将表达式'a.Claims.Sum(c => c.TotalClaimAmount())'转换为SQL,并且无法将其视为本地表达式。

请帮帮我。非常感谢

2 个答案:

答案 0 :(得分:5)

LINQ无法将TotalClaimAmount方法调用转换为SQL表达式。

您可以做的是从TotalClaimAmount方法中提取表达式,并直接在Sum方法调用中使用它。

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

答案 1 :(得分:4)

SQL中的自定义方法没有相应的命令。所以编译器无法翻译你的表达式。而是首先获取您的项目,然后选择您的结果:

 var items = Applicants.Where(a => a.Claims.Any()).ToList();
 var results = items.Select(a => a.Claims.Sum(c => c.TotalClaimAmount());