gpt4 book ai didi

c# - Linq to sql 查询 : how to prevent duplication of code

转载 作者:行者123 更新时间:2023-11-30 20:57:14 24 4
gpt4 key购买 nike

我的问题

我是 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),

});

问题

如何编写我的查询,以便在我的代码中仅编写一次公共(public)部分?

最佳答案

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

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

关于c# - Linq to sql 查询 : how to prevent duplication of code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16985118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com