I have the following tables mapped with Entity Framework:
Invoices (InvoiceID, InvoiceNumber, IsPaid)
Parts (PartID, PartNumber, OrganisationID, IsActive)
Invoices_Parts (InvoiceID, PartID, Quantity, IsClaimed)
I'm trying to get a List
of InvoiceIDs from the Invoices_Parts
table with a number of conditions. The condition I'm having a problem with is "where any Part
from Invoices_Parts
is active".
The code so far:
IQueryable<int> partIds = db.Parts.Where(x =>
x.OrganisationID == loggedInUser.OrganisationID).Select(y => y.PartID);
// && x.IsActive
List<string> invoiceIds = db.Invoices_Parts.Where(x =>
!x.IsClaimed && x.Invoice.IsPaid && partIds.Contains(x.PartID)
.DistinctBy(y => y.InvoiceID)
.Select(z => z.InvoiceID.ToString()).ToList();
I've commented out "&& x.IsActive" because I want the list of InvoiceIDs to be such that at least one part must meet the IsActive condition - I don't want to filter out all the parts where IsActive is false. How do I achieve this in LINQ without manually looping through collections and adding/removing items?
Note: In case anyone is wondering, I'm using the following helper method for DistinctBy
:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
Edit: I have the following properties on each entity:
Invoice:
public virtual ICollection<Invoices_Parts> Invoices_Parts { get; set; }
Part:
public virtual ICollection<Invoices_Parts> Invoices_Parts { get; set; }
Invoices_Parts:
public virtual Invoice Invoice { get; set; }
public virtual Part Part { get; set; }