I have a test method which I'd like to return a query which should have OR condition based on input.
Let's say I input 3 statuses [New, IsProcessing, Done] and I want the query to return Payments which have either status New, IsProcessing or Done.
I try to build the query by adding .Where condition but it returns 0 row. I think it's doing the AND condition so no data as there's no payment having 3 statuses. Every single payment can have only 1 status.
public IQueryable<Payment> GetPaymentQuery(List<PaymentStatus> statuses)
{
IQueryable<Payment> query = _dbContext.Payment.AsQueryable();
if (statuses != null && statuses.Any())
{
if (statuses.Contains(PaymentStatus.New))
{
query = query.Where(x => x.Status == PaymentStatus.New);
}
if (statuses.Contains(PaymentStatus.IsProcessing))
{
query = query.Where(x => x.Status == PaymentStatus.IsProcessing);
}
if (statuses.Contains(PaymentStatus.Done))
{
query = query.Where(x => x.Status == PaymentStatus.Done);
}
}
return query;
}
public enum PaymentStatus{
New, IsProcessing, Done, Cancelled
}
Please can you advise?
Thanks
CodePudding user response:
You can avoid this by capturing it all in one Where
clause using Contains
:
public IQueryable<Payment> GetPaymentQuery(List<PaymentStatus> statuses)
{
IQueryable<Payment> query = _dbContext.Payment.AsQueryable();
if (statuses != null && statuses.Any())
{
var validStatuses = status.Where(x => x != PaymentStatus.Cancelled).Distinct();
query = query.Where(x => validStatuses.Contains(x));
}
return query;
}