如何在带有条件多个where条件的Entity Framework中编写查询? [英] How to write query in Entity Framework with conditional multiple where condition?

查看:304
本文介绍了如何在带有条件多个where条件的Entity Framework中编写查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a wcf application which is connecting to DB to get some data for customer using Entity Framework. The concept is to search a customer based on the search parameters. User can provide all or few or at least one of the search parameters. But I am quite new in Entity Framework and getting confused on how to do this. I can do this in traditional SQL coding by considering If - Else condition in c# side.

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

This is my code which is getting the all of the paramters:

   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);

请帮我建议如何只用很少或一个参数得到结果。
谢谢

Please help me by suggesting how do I get the result with few or one parameter only. Thanks

推荐答案

实体框架查询是延迟查询。在您开始要求结果之前,它们实际上并没有运行。这意味着您可以分段构建查询,并且(大部分)它的工作原理与一个更大的查询完全相同。

Entity Framework queries are "deferred" queries. They don't actually run until you start asking for results. This means you can build up a query in pieces and it will (mostly) work exactly like one bigger query.

对于您来说,您可以执行以下操作:

In your case, you can do something like:

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查询中,以对您的数据运行。

etc. At the end, when you execute the customers query (for example, call ToList or use a foreach loop) EF will consolidate all of those smaller Where clauses into a single SQL query to run against your data.

这篇关于如何在带有条件多个where条件的Entity Framework中编写查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆