I have a small issue with EF. I’m performing a query on a large table, and it takes very long. I think I found the cause, but cannot find a solution;
My LINQ query looks like this:
IEnumerable<string> o = (from P in Table where P.ITEMID == itemid && P.IMAGESIZE == size select P.PATH);
return o.Any() ? o.FirstOrDefault() : null;
I expect this to produce a SQL query with a where clause, but what it actually produces is this:
SELECT
[Extent1].[ITEMID] AS [ITEMID],
[Extent1].........
snap 10 columns
FROM [dbo].[TABLE] AS [Extent1]
The where clause and select (I try to select only one column) are executed after enumeration. What I want it to do is to produce a SQL query with the where clause and select only one column.
What am I doing wrong?
Since you are creating an
IEnumerable<string>type of object, EF runs this query in the first line. ThenAny()orFirstOrDefault()are executed in the memory set.If you want to “continue” writing linq statements and run the query in the end; just go with
IQueryable<T>.but as Ryan Bennett suggested, it is easier to use;