Home > Blockchain >  IQueryable Adding OR Conditions to the chain of queries
IQueryable Adding OR Conditions to the chain of queries

Time:02-08

How can i Chain EF queries with OR condition

Right now i am chaining or building the query like below and this is ended up adding AND conditions

              if (model.EMailChoices?.Count() > 0)
                {
                    query = query.Where(
                                        c => model.EMailChoices.Contains(c.Contact.CommunicationPreferences.TPEMail)
                                        );
                }

                if (model.MailChoices?.Count() > 0)
                {
                    query = query.Where(
                                        c => model.MailChoices.Contains(c.Contact.CommunicationPreferences.TPMail)
                                    );
                }

                if (model.PhoneChoices?.Count() > 0)
                {
                    query = query.Where(
                                        c => model.PhoneChoices.Contains(c.Contact.CommunicationPreferences.TPTelephone)
                                    );
                }

How can we add OR conditions to this chain

CodePudding user response:

bool anyEmails = model.EMailChoices?.Any() == true;
bool anyMails = model.MailChoices?.Any() == true;
bool anyPhones = model.PhoneChoices?.Any() == true;

if(anyEmails || anyMails || anyPhones)
{
     query = query.Where( 
         c => (anyEmails && model.EMailChoices.Contains(c.Contact.CommunicationPreferences.TPEMail))
           || (anyMails && model.MailChoices.Contains(c.Contact.CommunicationPreferences.TPEMail))
           || (anyPhones && model.PhoneChoices.Contains(c.Contact.CommunicationPreferences.TPTelephone)));
}
  •  Tags:  
  • Related