簡體   English   中英

Linq to sql查詢:如何防止代碼重復

[英]Linq to sql query: how to prevent duplication of code

我的問題

我對Linq很新,我不得不使用它。 我編寫了函數查詢,但我被迫在每個查詢中復制一些代碼。 查詢的第一部分就是給出數據庫的結構並刪除損壞的數據,所以它始終是相同的,並且它不希望在我的代碼中有多個版本。

我嘗試了什么

我做了一個函數返回查詢的一部分,但它不會編譯,只是給出一個意外的令牌錯誤,所以我迷路了。

我的代碼

//always the same in each query : beginning
     IQueryable<Lead> query = (from costumers in dc.T_costumers
                                      join demands in dc.T_Demands on costumers.Costumer_FK equals typo.Typoe_PK
                                      where
                                          (dc.ISNUMERIC(costumers.Geoloc) == true) &&
                                          costumers.longitudeClient != null 
                                      where (dc.ISNUMERIC(shop.id) == true) 
//always the same in each query : end
                                       where (temps.Date > new DateTime(2013, 4, 1).Date)
                               select new Lead
                                           {
                                               id = Convert.ToInt32(costumers.id),

                                           });

我如何編寫查詢,以便公共部分只在我的代碼中編寫一次?

您可以拆分查詢。 首先 - 選擇包含所有鏈接實體的匿名對象:

 var query = 
       from leads in dc.T_DM_FactDemandeWebLeads
       join demands in dc.T_DM_DimDemandeWebs 
            on leads.DemandeWeb_FK equals demands.DemandeWeb_PK
       join temps in dc.T_DM_Temps 
            on demands.DateDemande_FK equals temps.Temps_PK
       join distributeurs in dc.T_DM_DimDistributeurs 
            on leads.Distributeur_FK equals distributeurs.Distributeur_PK
       join geographies in dc.T_DM_DimGeographies 
            on distributeurs.DistributeurGeographie_FK equals geographies.Geographie_PK
       join typologies in dc.T_DM_DimTypologies 
            on leads.Typologie_FK equals typologies.Typologie_PK
       where (dc.ISNUMERIC(leads.GeolocDistanceRouteDistrib) == true) &&
              leads.longitudeClient != null && typologies.CodeProcessus == "LEAD"
       where (dc.ISNUMERIC(distributeurs.DistribIdPointDeVente) == true) 
       select new { 
           leads, 
           demands, 
           temps, 
           distributeurs,
           geographies,
           typologies
       };

第二 - 寫特定查詢:

  var leads = from x in query
              where (x.temps.Date > new DateTime(2013, 4, 1).Date)
              where (x.temps.Date < new DateTime(2013, 5, 30).Date)
              select new Lead {
                  id = Convert.ToInt32(x.leads.DemandeWeb_FK),
              });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM