我有一种情况,我需要在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);
}
}
答案 0 :(得分:2)
另一种方法可能是改变您组织零售商和客户的方式。假设客户/零售商都是潜在客户,则与潜在客户具有继承关系。
Customer : Lead
以及
Retailer : Lead
您现在可以拥有Address(而不是HomeAddress和ShopAddress)的通用属性。 现在您已经将上面的结构减半了。 接下来,您可以拥有三个谓词,每个谓词分别用于乡村街道和大头针,并且仅在输入字符串为非空时使用。您可以根据存在情况选择下一个或三个谓词。
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));