2010-08-20 54 views
0

我有一个基本的搜索控件,根据预定义的搜索/过滤标准,通过下拉列表从CRM中列出公司。每个DropDown的默认选择是“ALL”,否则用户选择一个特定的项目。我希望能够基于选择动态地构建一个Linq查询。在5个选择器中,他们提供了可以匹配公司表的值,但是其中两个选择器(如果选择了其中一个或两个)将需要一个连接或连接,否则不应再次执行基本结果集的操作。我希望这是有道理的。添加条件动态加入Linq

我不知道如何有效地做到这一点。这里是我的代码:

private void Search() 
{ 
    EnergyPubsCRMDataContext dc = new EnergyPubsCRMDataContext(); 

    var results = (from c in dc.Companies 
        select c); 


    //only create the join if the selected index > 0 
    if (ddlIndustry.SelectedIndex > 0) 
    { 
     //A company can be in 1 or more industries, thus here I want to join 
     //with the CompanyIndustry table and have a WHERE clause to match on the ddlIndustry.SelectedValue 
    } 

    //only create the join if the selected index > 0 
    if (ddlServices.SelectedIndex > 0) 
    { 
     //A company can offer 1 or more services. Here I want to join to the CompanyService table 
     //on the CompanyID and have a WHERE clause to match the ddlServices.SelectedValue 
    }   

    //These work OK to shape the overal query further (they don't need joins) 
    if (ddlCountry.SelectedIndex > 0) 
     results = results.Where(c => c.CountryID == Convert.ToInt32(ddlCountry.SelectedValue)); 

    if (ddlStateRegion.SelectedIndex > 0) 
     results = results.Where(c => c.StateRegionID == Convert.ToInt32(ddlStateRegion.SelectedValue)); 

    if (ddlAccountManagers.SelectedIndex > 0) 
    { 
     Guid g = new Guid(ddlAccountManagers.SelectedValue); 
     results = results.Where(c => c.UserId == g); 
    } 

    results = results.OrderBy(c => c.CompanyName); 

    //Bind to Grid....   
} 
+0

我不知道,但也许这可以将您指向正确的方向:http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx – Jeroen 2010-08-20 20:43:00

回答

0
if (ddlIndustry.SelectedIndex > 0) 
{ 
    //A company can be in 1 or more industries, thus here I want to join 
    //with the CompanyIndustry table and have a WHERE clause to match on the ddlIndustry.SelectedValue 
    results = results.Where(c => c.CompanyIndustry.IndustryID == ddlIndustry.SelectedValue); 
} 

假设你已经在你的数据库/ DBML正确的外键。

这将隐式生成连接。

0

我有非常相似的问题,没有外键我可以利用。 我的解决方案将转换为这样的事情:

results = results 
    .Join(dc.CompanyIndustry, c => c.CompanyID, ci => ci.CompanyID, (c, ci) => new { c, ci.IndustryID }) 
    .Where (a => a.IndustryID == ddlIndustry.SelectedValue) 
    .Select(a => a.c); 

基本上是:

1)首先,我们创建一个连接,用投影,让我们IndustryID(加入)

2)我们过滤器的基础在IndustryID(在哪里)

3)我们回到原来的匿名类型,这样我们就可以修改原来的查询(选择)