-3

I have this linq code that I need to translate into identical SQL so I can query the database directly... I get stuck when it gets complicated. Can anyone help?

Linq

_db.BatchPaymentSplits
    .Where(bps => bps.YearSetupId == i.YearSetupId)
    .Where(bps => bps.CustomerIdEntered != null)
    .Where(bps => _db.BatchPayments
        .Where(bp => _db.Batches.Where(b => b.BatchTypeId.Equals("T"))
                                .Select(b => b.BatchId)
                                .Contains(bp.BatchId)
        )
        .Select(bp => bp.BatchPaymentId).Contains(bps.BatchPaymentId)
    )

SQL so far

SELECT * FROM BatchPaymentSplit
WHERE YearSetupId = 1
AND CustomerIdEntered IS NOT NULL
CheezStix
  • 59
  • 2
  • 15

1 Answers1

1

I can't say that I think the LINQ or the resulting SQL is the best way to express this query (should be using Join I think), but this is my literal translation:

SELECT *
FROM BatchPaymentSplits bps
WHERE bps.YearSetupId = i.YearSetupId AND
      bps.CustomerIdEntered IS NOT NULL AND
      EXISTS (SELECT * FROM BatchPayments bp
              WHERE EXISTS (SELECT * FROM Batches b
                            WHERE b.BatchTypeId = 'T' AND
                                  b.BatchId = bp.BatchId) AND
                    bp.BatchPaymentId = bps.BatchPaymentId)

You can translate Contains when applied to an IEnumerable/IQueryable as an EXISTS query with an = expression.

NetMage
  • 26,163
  • 3
  • 34
  • 55