2010-08-20 55 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)我們回到原來的匿名類型,這樣我們就可以修改原來的查詢(選擇)