logo

C# - Using IEnumerable to add a where clause for the ICollection

Overview: The IEnumerable of type Invoice is used to filter on InvoiceId for the ResultList IQueryable type returned by GetObjectsAsync. The IEnumerable can be foreach to movenext through the list. The virtual ICollection allows for lazy loading if the base class provides for it.

Virtual

Virtual is used if lazy loading or change tracking is on.

public virtual ICollection<Invoice> Invoices { get; set; } 

Using IEnumerable to add a where clause for the ICollection

public IList<InvoiceView> GetInvoicesByCustomerId(int customerId, Expression<Func<Customer, bool>> customerPredicate, int? invoiceId)
        {
            IEnumerable<Invoice> invoiceList = null;
            var resultList = base.GetObjectsAsync(customerPredicate, "invoices").FirstOrDefault();

            IList<InvoiceView> list = new List<InvoiceView>();
            if (invoiceId != null)
            {
                invoiceList = resultList.Invoices.Where(f => f.InvoiceId == invoiceId);
            }
            else
            {
                invoiceList = resultList.Invoices;
            }
            
            foreach (var item in invoiceList)
            {
                list.Add(applicationViewFactory.MapInvoiceView(item));
            }
            return list;

        }

base.GetObjectsAsync


 public IQueryable<T> GetObjectsAsync(Expression<Func<T, bool>> predicate,string includeTable="")
        {
            IQueryable<T> result = _dbContext.Set<T>().Where(predicate);
            if (includeTable != "")
            {
                result=result.Include(includeTable);
            }
                
            
                return result;
        }
s