如何在 IQueryable EF 中的 WHERE() 中添加表达式 ANY()



我有一个场景,我需要在 WHERE(( 条件的 ANY(( 中添加条件

IQueriable<Lead> c = DBContext.Lead;
if(Retailer)
{
if(!string.IsNullOrEmpty(country))
{
c = c.Where(x=> x.Retailer.ShopAddress.Any(s=>s.country == country);
}
if(!string.IsNullOrEmpty(street))
{
c = c.Where(x=> x.Retailer.ShopAddress.Any(s=>s.street== street);
}
if(!string.IsNullOrEmpty(pin))
{
c = c.Where(x=> x.Retailer.ShopAddress.Any(s=>s.pin== pin);
}
}else
{
if(!string.IsNullOrEmpty(country))
{
c = c.Where(x=> x.Customer.HomeAddress.Any(s=>s.country == country);
}
if(!string.IsNullOrEmpty(street))
{
c = c.Where(x=> x.Customer.HomeAddress.Any(s=>s.street== street);
}
if(!string.IsNullOrEmpty(pin))
{
c = c.Where(x=> x.Customer.HomeAddress.Any(s=>s.pin== pin);
} 
}
  • 我需要在 ANY(( 中添加条件作为类似方法,因此如果给定街道和 pin,那么它需要在同一记录上。
  • 这里的结果将类似于 OR 条件。
  • 如何使用方法代替 ANY(( 将其作为具有条件添加条件的单个 ANY 返回?
  • 我只需要在 lambda 上使用它。

另一种方法是改变您组织零售商和客户的方式。假设客户/零售商都是潜在顾客,则与潜在顾客具有继承关系。

Customer : Lead 

以及

Retailer : Lead

您现在可以拥有"地址"的通用属性,而不是"家庭地址"和"商店地址"。 现在你已经把上面的结构减半了。 接下来,您可以有三个谓词,分别用于乡村街道和固定,并且仅在输入字符串不为空时使用。你可以根据存在来下一个或三个谓词。

Predicate<Address> countryPred = new Predicate<Address>(a => a.country == country);
Predicate<Address> streetPred = new Predicate<Address>(a => a.street == street);
Predicate<Address> pinPred = new Predicate<Address>(a => a.pin== pin);
Predicate<Address> finalPred;
if(string.IsNullOrEmpty(country))
{
if(finalPred == null)
finalPred = countryPred;
else
finalPred = c => finalPred (c) || countryPred (c);
}
..
..
..
c = c.Where(x=> x.Lead.Address.Any(s=> finalPred));

相关内容

最新更新