I have this query below that looks for a transfer with a user id in either the SenderId or ReceiverId column.
// transferParams.Transfer = null,1,2
var transfersCount = await _dbContext.Transfers
.Where(p =>
(p.SenderId == userFromRepo.Id || p.ReceiverId == userFromRepo.Id) &&
(!transferParams.Status.HasValue || p.TransferStatus == (TransferStatus)transferParams.Status) &&
(!transferParams.Type.HasValue || p.TransferType == (TransferType)transferParams.Type))
.CountAsync();
I’ve now passed in another parameter in the controller called ‘Transfer’ that’s a nullable Int where 1 is Received and 2 is Sent.
I need to refactor the query so that if the transfer parameter that’s passed in is null I will still look in both columns (ReceiverId, SenderId), but if it’s 1 then I’ll only look in the ReceiverId column and if 2 only look in the SenderId column.
Can anyone tell me how to do this?
>Solution :
var baseQuery = _dbContext.Transfers.AsQueryable();
switch(transfer)
{
case 1:
baseQuery = baseQuery.Where(p => p.ReceiverId == user.Id);
break;
case 2:
baseQuery = baseQuery.Where(p => p.SenderId == user.Id);
break;
default:
baseQuery = baseQuery.Where(p => p.ReceiverId == user.Id || p.SenderId == user.Id);
break;
}
if (transferParams.Status.HasValue)
baseQuery = baseQuery.Where(p=> p.TransferStatus == (TransferStatus)transferParams.Status);
if (transferParams.Type.HasValue)
baseQuery = baseQuery.Where(p => p.TransferType == (TransferType)transferParams.Type);
var transferCount = await baseQuery.CountAsync();