How can we achieve many to many with dataLoader?
Lets say i want to fetch the companies with there contacts (and a contact can have multiple companies). I have a companyLinks as midde table (with companyId/contactId).
I have this which works when there is only 1 contact for a company:
public async Task<ILookup<Guid, Contact>> GetContactsFromCompanyBatchAsync(IEnumerable<Guid> companyIds)
{
var contacts = _entities.Include(c => c.CompanyLinks).Where(contact => contact.CompanyLinks.Any(cl => companyIds.Contains(cl.CompanyId)));
return contacts.ToLookup(cont => {
var res = cont.CompanyLinks.Any() ? cont.CompanyLinks.ElementAt(0).CompanyId : Guid.Empty;
return res;
});
}
But what if a contact has more then 1 company? How can i know the correct companyId ?
Thanks to sungram3r for the hint. Solution is to start from the joining-table.
public async Task<ILookup<Guid, Contact>> GetContactsFromCompanyBatchCollectionAsync(IEnumerable<Guid> companyIds)
{
var companyContacts = _salesNoteContext.CompanyContact
.Where(contactCompany => companyIds.Contains(contactCompany.CompanyId))
.Include(contactCompany => contactCompany.Company);
return companyContacts.ToLookup(contactCompany => contactCompany.CompanyId, contactCompany => contactCompany.Contact);
}