views:

1313

answers:

5

I am having some problems with linq to entities in the ado.net entity framework. Basically what I'm doing is this:

var results = (from c in companies
 where c.Name.StartsWith(letter)
 select c);

and this gets translated to SQL as something like:

WHERE (CAST(CHARINDEX(@p, [Extent1].[Name]) AS int)) = 1

which is fine but my table has millions of records so this runs VERY slow. What I need it to generate is something like:

WHERE Name LIKE @p + '%'

I'm searched high and low and cannot find any solutions except to either use a stored procedure or use entity sql...

Is there any way to do this through linq? Possibly by somehow extending the linq to entities linq provider, or somehow intercepting the command tree or generated query?

Please help!

+2  A: 

Wow, that is a truly bizarre way of doing it! Note that LINQ-to-SQL (in this case) uses LIKE @p0 + '%'... very odd.

Which EF provider (database) are you using? SQL Server?

As you say, a stored procedure will the the job, but you shouldn't have to do that... very, very odd...

Marc Gravell
Yes I'm using SQL Server 2005. From what I've read, LINQ to SQL provides a SqlMethods class that exposes SQL functions and operators such as LIKE but there's no such thing in LINQ to Entities. Go figure...
+3  A: 
Andrew Robinson
Provided you have an index on the Note/Name column and cardinality's not too low, it will be used on a LIKE 'a%' query. I'm not sure the query optimizer will be able to use the index for a CAST(CHARINDEX()) operation.
Mark S. Rasmussen
I have an index on the Name column of my database. The LIKE does an index scan, the generated SQL (CHARINDEX) does a table scan which is why it takes so long.
A: 

Is "letter" a char? If you made it a string, what happens?

var results = (from c in companies
    where c.Name.StartsWith(letter.ToString())
    select c);
ajma
It is a string...
A: 

I tried using this syntax instead

Name.Substring(0, 1) == "E"

This SQL is generated

WHERE N'E' = (SUBSTRING([Name], 0 + 1, 1))

Maybe this is more efficient?

slamidtfyn
Yes I've tried that too... I think it ran about the same.
+1  A: 

This is a known issue with Linq to Entities. Unlike LIKE, apparently this construct doesn't use indexes.

We've had some success using Substring (which translates to SUBSTRING). The execution plan is similar, but in our case the query executes far quicker.

It's another "I'm sure it will be fixed in EF 2"... :-(

Pete Montgomery