繁体   English   中英

如何在条件多重条件的情况下在实体框架中编写查询?

[英]How to write query in Entity Framework with conditional multiple where condition?

我正在创建一个wcf应用程序,它连接到DB以使用Entity Framework为客户获取一些数据。 该概念是基于搜索参数搜索客户。 用户可以提供全部或几个或至少一个搜索参数。 但我在实体框架中相当新,并且对如何做到这一点感到困惑。 我可以通过考虑c#侧的If - Else条件在传统的SQL编码中执行此操作。

这是我的代码,它获取了所有的参数:

   var customers = from o in natCustomer.CustomerLists
                    select o;

    customers = customers.Where(c => c.Name == sName && c.Age == iAge
        && c.Gender == sGender && c.Height == dHeight && c.Weight == dWeight                             
        && c.Nationality == sNationality
        && c.EyeColor == sEyeColor && c.SpecialMark == sSpecialMark);

请通过建议如何仅使用少量或一个参数来获得结果来帮助我。 谢谢

实体框架查询是“延迟”查询。 直到你开始要求结果,它们才会真正运行。 这意味着您可以逐段构建查询,它(大部分)将完全像一个更大的查询。

在您的情况下,您可以执行以下操作:

var customers = from o in natCustomer.CustomerLists
                select o;

if (!string.isNullOrEmpty(sName)) 
  customers = customers.Where(c => c.Name == sName);

if (!string.isNullOrEmpty(sNationality)) 
  customers = customers.Where(c => c.sNationality == sNationality);

if (!string.isNullOrEmpty(SpecialMark )) 
  customers = customers.Where(c => c.SpecialMark == SpecialMark);

最后,当您执行customers查询时(例如,调用ToList或使用foreach循环),EF会将所有较小的Where子句合并到一个SQL查询中以针对您的数据运行。

假设您只想查找与所有非空参数匹配的客户,另一种方法是在where查询中包含空检查,并且仅在参数不为null时将参数与客户数据进行比较。

customers = customers.Where(c => (string.isNullOrEmpty(sName) || c.Name == sName) 
    && (iAge == null || c.Age == iAge)
    && (string.isNullOrEmpty(sGender) || c.Gender == sGender));

您需要某种方法来确定是否设置了给定的输入。 为简化起见,我假设您接收的参数为nullables。 因此,如果提供了参数,您可以添加其他条件:

customers = sName == null ? customers : customers.Where(c => c.Name == sName);
customers = iAge == null ? customers : customers.Where(c => c.Age == iAge);
customers = sGender == null ? customers : customers.Where(c => c.Gender == sGender);
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM