IQueryable 添加 OR 条件到查询链
IQueryable Adding OR Conditions to the chain of queries
如何使用 OR 条件链接 EF 查询
现在我正在像下面这样链接或构建查询,这最终添加了 AND 条件
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)
);
}
我们如何向这条链添加 OR 条件
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)));
}
如何使用 OR 条件链接 EF 查询
现在我正在像下面这样链接或构建查询,这最终添加了 AND 条件
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)
);
}
我们如何向这条链添加 OR 条件
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)));
}