使用包含和包含的 LINQ

LINQ using Contain with Include

我有以下代码可以正常工作:

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();

我想将其重构如下以使用 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();

唯一的问题是我无法弄清楚Contains。我正在传递包含 CompanyIds 的可枚举整数,我只想获得这些公司及其子项。

关系是:公司有产品,产品有授权,授权有付款。

这应该有效:

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))

试试这个:

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

您可以将单个 where 子句与“&&”运算符一起使用