Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query taking too long

I wonder if someone can help me with this. I have a LINQ query - no problems with it, but it takes far too long to return data

var result = Context.paf_wgs84.Where(c => c.Postcode.Contains(postcode)).Take(15);

Very simple, the idea as the user is typing, using AJAX, it returns a set of 15 possible matches.

The problem is, there are 1.6 million records

Running the following code in management studio takes around 3 seconds

SELECT   code
FROM     paf_wgs84
WHERE    (code LIKE '%EC1%')

where as running the following code takes less than a second

SELECT   TOP 15  code
FROM     paf_wgs84
WHERE    (code LIKE '%EC1%')

Is there a way of doing something similar in LINQ without using .take()?

like image 425
Matt Avatar asked Aug 25 '11 10:08

Matt


1 Answers

You can try something like this. This will only return one column.

var result = Context.paf_wgs84.Where(c => c.Postcode.Contains(postcode)).Select(x=>new {x.Postcode}).Take(15);

The generated Sql statement will look like this.

/*
-- Region Parameters
DECLARE @p0 VarChar(1000) = '%s%'
-- EndRegion
SELECT TOP (15) [t0].[code]
FROM [paf_wgs84] AS [t0]
WHERE [t0].[code] LIKE @p0
*/
like image 194
Jethro Avatar answered Sep 21 '22 16:09

Jethro