Is this the correct way to use foreach loops whist using async ? Is there a better more efficient way? IAsyncEnumerable? (Ignore the fact that the two tables could be joined together this is a simple example)
public async Task<IList<ContactAndAccounts>> GetAll()
{
var accounts = await _dbContext.Account.Where(x => x.Name == "Amazing").ToListAsync();
foreach(var account in accounts)
{
accounts.Contacts = await GetContact(account.Id);
}
return accounts;
}
public async Task<IList<contact>> GetContact(Guid id)
{
return await _dbContext.Contact.Where(x => x.AccountLinkId = id).ToListAsync();
}
I agree with Johnathan Barclay's answer but would say that from a database perspective you might find it is faster to do a single query big query than lots of small queries.
Doing one query and passing in all of your ids is usually less expensive than multiple seperate queries.
public async Task<IList<ContactAndAccounts>> GetAll()
{
var accounts = await _dbContext.Account.Where(x => x.Name == "Amazing").ToListAsync();
var contacts = await GetContacts(accounts.Select(o => o.Id));
// Map contacts to accounts in memory
return accounts;
}
public async Task<IList<contact>> GetContacts(List<Guid> ids)
{
return await _dbContext.Contact.Where(x => ids.Contain(x.AccountLinkId)).ToListAsync();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With