Linq到sql查询:如何防止代码重复

本文关键字:何防止 代码 sql 查询 Linq | 更新日期: 2023-09-27 18:17:27

我的问题

我刚接触Linq,使用起来有困难。我已经编写了函数查询,但我被迫在每个查询中复制一些代码。查询的第一部分只是在那里给出数据库的结构和删除损坏的数据,所以它总是相同的,它不想在我的代码中有几个版本。

What I tried

我创建了一个函数返回查询的部分,但它不会编译,只是给出一个意外的标记错误,所以我迷路了。

我的代码

//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),
                                           });

我如何写我的查询,所以公共部分只写一次在我的代码?

Linq到sql查询:如何防止代码重复

可以拆分查询。首先-选择所有链接实体的匿名对象:

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

Second - write specific query:

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