Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I refactor this EF Core query to add another where condition variable?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading