LINQ子查询的性能非常慢

时间:2016-12-07 18:17:03

标签: c# performance entity-framework linq asp.net-web-api

在C#中执行LINQ子查询时,我遇到了性能问题。 查询如下:

var _result = _db.Prices
            .Join(_db.Vendors,
            e => e.VendorId,
            v => v.VendorId,
            (e, v) => new {
                TotalPrice = e.TotalPrice,     
                Vendor = v.Title,               
                AmountPaid = _db.Amounts
                    .Where(p => p.PrId == e.PrId )
                    .GroupBy(p => p.PrId )
                    .Select(grp => (decimal?)grp.Sum(k => k.AmountPaid) ?? 0M)    
                    .FirstOrDefault()  
            });

价格,供应商和金额是实体框架对象。

首先,我正在VendorId上进行Price to Vendors表的连接,结果我正在添加一个计算字段AmountPaid。结果是一个子查询,它返回Amounts表中与PrId索引匹配的给定记录的AmountPaid列的总和。 以上所有内容都作为ASP.NET web api中的JSON对象返回。

以上对数据库中记录的结果仅为1992行。 上述命令需要大约20秒才能返回结果。如果我删除了AmountPaid计算,它只需要1秒钟。

如果我在SQL Server studio中运行等效的SQL命令,它只需要半秒,并且包含AmountPaid计算:

SELECT Prices.*, Vendors.Title, 
AmountPaid = (SELECT SUM(AmountPaid) from Amounts where Amounts.PrId = Prices.PrId GROUP BY PrId) FROM Amounts 
INNER JOIN Vendors ON Amounts.VendorId = Vendors.VendorId

有没有办法解决这个问题? 我无法理解这个问题,因为SQL命令在执行时没有问题。 LINQ语法是否有错误,或者在LINQ中获取相同结果集的另一种方法是什么?

0 个答案:

没有答案