如何将Lambda Expression转换为SQL exp?

时间:2017-09-19 05:46:31

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

我将此表达式转换为SQL表达式时遇到困难。我尝试了各种应用,但我失败了。我试图自己转换,但结果不同。

db.Trans_SAPStat.Where(s => s.EmployeeID == EmployeeID && s.PaymentID != PaymentID && !s.Status.Equals("cancelled or", StringComparison.OrdinalIgnoreCase))
                                           .Join(_db.Trans_PaymentDetail,
                                               stat => stat.PaymentID,
                                               paydet => paydet.PaymentID,
                                               (stat, paydet) => new
                                               {
                                                   InvoiceNo = paydet.Remarks,
                                                   paydet.Amount,
                                                   stat.Status,
                                                   paydet.PaymentCode
                                               })
                                           .Where(s => s.PaymentCode.ToLower() == "c")
                                           .GroupBy(g => g.InvoiceNo)
                                           .Select(lg =>
                                                   new
                                                   {
                                                       InvoiceNo = lg.Key,
                                                       TotalAmount = lg.Sum(w => w.Amount)
                                                   }).ToList();

3 个答案:

答案 0 :(得分:0)

如果您在工作应用程序中有此代码,则尝试使用SQL事件探查器。另一个选择 - linqpad

答案 1 :(得分:0)

试试这个:

SELECT
  p.Remarks AS InvoiceNo,SUM(p.Amount) AS TotalAmount
FROM Trans_SAPStat AS s
INNER JOIN Trans_PaymentDetail AS p ON s.PaymentID = p.PaymentID
WHERE s.EmployeeID = @EmployeeID 
  AND s.PaymentID <> @PaymentID 
  AND LOWER(s.Status) <> 'cancelled or'
  AND LOWER(s.PaymentCode) = 'c'
GROUP BY p.Remarks

答案 2 :(得分:0)

您可以尝试将查询设置为变量而不实现(.ToList()),然后只使用query.ToString()。这将返回实际的SQL查询。

var query = db.Trans_SAPStat.Where(....); // don't call .ToList()
var sqlQuery = query.ToString();
var result = query.ToList(); // materialization

注意:这是实体框架/ linq到实体IQueryable<T>接口的默认行为。