Ben
Ben

Reputation: 969

LINQ using Contain with Include

I have the below code which works fine:

var payments = from tCompany in _dataContext.Companies
            join tProduct in _dataContext.Products on tCompany.CompanyId equals tProduct.CompanyId
            join tMandate in _dataContext.Mandates on tProduct.ProductId equals tMandate.ProductId
            join tPayment in _dataContext.Payments on tMandate.MandateId equals tPayment.MandateId
            where companyIds.Contains(tCompany.PlatformCompanyId)
            && (tPayment.PaymentReceivedGCUtc >= fromDate && tPayment.PaymentReceivedGCUtc <= toDate)
            select new SubscriptionFeesWithCompanyId()
            {
               PlatformCompanyId = tCompany.PlatformCompanyId,
               Amount = tPayment.Amount,
               PaymentReceivedAt = tPayment.PaymentReceivedGCUtc,
               PaymentId = tPayment.PaymentId
            };

        return payments.ToList();

I would like to refactore it as below to use Include():

var payments = _dataContext.Payments
                .Include(p => p.Mandate)
                .Include(p => p.Mandate.Product)
                .Include(p => p.Mandate.Product.Company);

            var filteredPayments = payments
                .Where(p => p.PaymentReceivedGCUtc >= fromDate)
                .Where(p => p.PaymentReceivedGCUtc <= toDate);

            var filteredPayments2 = filteredPayments.ToList();

The only problem is I can't figure out the Contains. I am passing an Enumerable int of CompanyIds in contains which I would like to get only those companies and its children.

The relation is: Company has Products, Product has Mandates, Mandate has Payments.

Upvotes: 0

Views: 543

Answers (2)

kgzdev
kgzdev

Reputation: 2885

Try this:

var filteredPayments = payments.Where(p => p.PaymentReceivedGCUtc >= fromDate && 
                                           p => p.PaymentReceivedGCUtc <= toDate && 
               companyIds.Contains(p.Mandate.Product.Company.PlatformCompanyId));

You can use single where clause with '&&' operators

Upvotes: 1

OlegI
OlegI

Reputation: 6010

This should work:

var payments = _dataContext.Payments
                .Include(payments => payments.Mandate)
                .ThenInclude(mandates => mandates.Product)
                .ThenInclude(products => products.Company)
                .Where(p => companyIds.Contains(p.Mandate.Product.Company.PlatformCompanyId))

Upvotes: 4

Related Questions