简体   繁体   中英

Improve query generated from entity framework

I have a query linq like this:

var query = from c in Context.Customers select c;
var result = query.ToList();

Linq query generate this tsql code:

exec sp_executesql N'SELECT 
[Project1].[Id] AS [Id], 
[Project1].[Name] AS [Name], 
[Project1].[Email] AS [Email]
FROM ( SELECT 
    [Extent1].[Id] AS [Id],
    [Extent1].[Name] AS [Name], 
    [Extent1].[Email] AS [Email]
    FROM [dbo].[Customers] AS [Extent1] ) AS [Project1]

Is there a way for not generate subquery?

Do you have any evidence that that query is causing performance problems? I imagine the query-optimizer would easily recognize that.

If you're certain after profiling that the query is a performance problem (doubtful) - and only then - you could simply turn the query into a stored procedure, and call that instead.

You use a tool like Linq because you don't want to write SQL, before abandoning that you should at least compare the query plan of your proposed SQL vs that generated by the tool. I don't have access to SQL Studio at the moment, but I would be a bit surprised if the query plans aren't identical...

EDIT: having had a chance to check out the query plans, they are in fact identical.

Short answer: No you cannot modify that query.

Long answer: If you want to reimplement Linq provider and query generator then perhaps there is a way but I doubt you want to do that. You can also implement custom EF provider wrapper which will take query passed from EF and reformat it but that will be hard as well - and slow. Are you going to write custom interpreter for SQL queries?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM