3

I'm running this query against a database:

var result = (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
                         where leads.longitudeClient != null && (Convert.ToInt32(leads.GeolocDistanceRouteDistrib) > 1000*30) && (temps.Date > new DateTime(2000, 1, 1).Date)
                         select new Lead
                         {

                             lng = leads.longitudeClient,     

                             lat = leads.latitudeClient,

                             distance = leads.GeolocDistanceRouteDistrib

                         }).Take(1000000);

Problem: This line is buggy:

(Convert.ToInt32(leads.GeolocDistanceRouteDistrib) > 1000*30)

as leads.GeolocDistanceRouteDistrib is a VARCHAR which takes "Unknown" in some cases, leading to a format exception:

Conversion failed when converting the varchar value 'Unknown' to data type int.

This problem is solved here, but the method cannot be converted to SQL.

Question: is there any way to rewrite the query so the conversion is done during the execution of the query?

Community
  • 1
  • 1
L. Sanna
  • 6,482
  • 7
  • 33
  • 47

2 Answers2

2

Use the technique in this answer to create the IsNumeric sql function in your dbml file. And use it in your query.

Something like this:

join  temps in dc.T_DM_Temps on demands.DateDemande_FK equals temps.Temps_PK
where dc.ISNUMERIC(leads.GeolocDistanceRouteDistrib) // Added!
where leads.longitudeClient != null && (Convert.ToInt32(leads.GeolocDistanceRouteDistrib) > 1000*30) && (temps.Date > new DateTime(2000, 1, 1).Date)
select new Lead
Community
  • 1
  • 1
Maarten
  • 22,527
  • 3
  • 47
  • 68
1

Add .AsEnumerable() to your entity, then you can use all mothods

var result = (from leads in dc.T_DM_FactDemandeWebLeads.AsEnumerable()
                         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
                         where leads.longitudeClient != null && (Convert.ToInt32(leads.GeolocDistanceRouteDistrib) > 1000*30) && (temps.Date > new DateTime(2000, 1, 1).Date)
                         select new Lead
                         {
                             lng = leads.longitudeClient,     
                             lat = leads.latitudeClient,
                             distance = leads.GeolocDistanceRouteDistrib
                         }).Take(1000000);
Raja A
  • 89
  • 1
  • 4