I have a query in Entity Framework Core like below:
var currencyRate = await AsyncExecuter.FirstOrDefaultAsync( from exchangeRate in await _exchangeRateRepository.GetQueryableAsync() where exchangeRate.CurrencyId == input.SelectedCurrencyId && exchangeRate.FirmId == input.FirmId && (exchangeRate.BeginDate <= input.ProcessDate && exchangeRate.EndDate >= input.ProcessDate) select exchangeRate.CurrencyRate); currencyRate = currencyRate / (await AsyncExecuter.FirstOrDefaultAsync( from exchangeRate in await _exchangeRateRepository.GetQueryableAsync() where exchangeRate.CurrencyId == input.CurrencyId && exchangeRate.FirmId == input.FirmId && (exchangeRate.BeginDate <= input.ProcessDate && exchangeRate.EndDate >= input.ProcessDate) select exchangeRate.CurrencyRate));
I am dividing one currencyRate to another from 2 queries. There are 2 select queries. Only difference between queries is where condition. How to do this in one select query?
Advertisement
Answer
Pull both rows with
where (exchangeRate.CurrencyId == input.CurrencyId || exchangeRate.CurrencyId == input.SelectedCurrencyId)
Put an explicit order by on like
order by exchangeRate.CurrencyId == input.CurrencyId ? 0 : 1
Now you know the two rows you get back are in (currencyid, selectedcurrencyid) order so you can eg ToArray them and do array[1] / array[0]