LINQ-用子查询加入

问题描述 投票:0回答:1

我正试图用LINQ实现以下查询

SELECT [flh].[InterestRate], [fld].[RegularPaymentAmount]
FROM [FactLoanDetail] AS [fld]
INNER JOIN [FactLoanHistory] AS [flh] ON [fld].[LoanKey] = [flh].[LoanKey]
 LEFT OUTER JOIN [FactLoanPayment] AS [flp]  ON ([flh].[LoanKey] = [flp].[LoanKey])
       AND flp.PostedDateKey = ( SELECT MAX(PostedDateKey) FROM FactLoanPayment 
                                 WHERE LoanKey = flh.LoanKey )
       AND flp.PaymentSequenceNumber = ( SELECT MAX(PaymentSequenceNumber) 
                                FROM FactLoanPayment WHERE LoanKey = flh.LoanKey )
WHERE [flh].[AsOfDateKey]  =  20200415;

这是为DataWarehouse和FactLoanPayment表没有PK,每个LoanKey和每个PostedDate可以有多条记录。我已经尝试过

var query = from fld in _dbContext.FactLoanDetail
    join flh in _dbContext.FactLoanHistory on fld.LoanKey equals flh.LoanKey
    join flp in _dbContext.FactLoanPayment on fld.LoanKey equals flp.LoanKey into lp
      from flp in lp.OrderByDescending(p => p.PostedDateKey)
                    .ThenByDescending(p => p.PaymentSequenceNumber)
                    .Take(1)
    where flh.AsOfDateKey == 20200415
    select new {flh.InterestRate, fld].[RegularPaymentAmount}

它编译得很好,但在运行时给我一个警告

orderby [p].PostedDateKey desc, [p].PaymentSequenceNumber desc' could not be translated and will be evaluated locally.

并试图从服务器返回每笔贷款的所有记录,而不仅仅是最新的记录。

我还尝试了

var query = from fld in _dbContext.FactLoanDetail
   join flh in _dbContext.FactLoanHistory on fld.LoanKey equals flh.LoanKey
   join flp in _dbContext.FactLoanPayment on fld.LoanKey equals flp.LoanKey into lp
       from flp in lp.OrderByDescending(p => p.PostedDateKey)
               .ThenByDescending(p => p.PaymentSequenceNumber).Take(1).DefaultIfEmpty()
   join dpm in _dbContext.DimPaymentMethod on flp.PaymentMethodKey equals dpm.PaymentMethodKey
   where flh.AsOfDateKey == asOfDateKey &&
         flp.PostedDateKey == _dbContext.FactLoanPayment.Where(p => p.LoanKey == flp.LoanKey).Max(m => m.PostedDateKey) &&
         flp.PaymentSequenceNumber == _dbContext.FactLoanPayment.Where(p => p.LoanKey == flp.LoanKey).Max(m => m.PaymentSequenceNumber)

这也是先重跑每笔贷款的所有记录。

有没有更好的方法来处理这个问题?

linq join subquery data-warehouse
1个回答
0
投票

解决方法是使用另一个表(dimLoan),它有一个对FLP表的引用作为虚拟属性,允许EF正确地解析关系。

var query = from fld in _dbContext.FactLoanDetail
  join dimLoan in _dbContext.DimLoan on flh.LoanKey equals dimLoan.LoanKey
  join flh in _dbContext.FactLoanHistory on fld.LoanKey equals flh.LoanKey
  join flp in _dbContext.FactLoanPayment on dimLoan.LoanKey equals flp.LoanKey
 where flh.AsOfDateKey == asOfDateKey &&
       flp.PostedDateKey == (
           dimLoan.FactLoanPayment
              .Where(m => m.LoanKey == flp.LoanKey)
              .Max(x => x.PostedDateKey)) &&
      flp.PaymentSequenceNumber == (
          dimLoan.FactLoanPayment
              .Where(m => m.LoanKey == flp.LoanKey)
              .Max(x => x.PaymentSequenceNumber)) 

© www.soinside.com 2019 - 2024. All rights reserved.