LINQ using Contain with Include

c# entity-framework-6 linq


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.

12/20/2019 1:54:54 PM

Accepted Answer

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))
12/20/2019 1:39:58 PM

Popular Answer

Try this:

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

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

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow