Question

To show my question I try to explain a sample:

Suppose that I have a table UsersInfo with these columns:

Id, UserName, Password, FName, LName, Gender, Birthday, 
HomeTel, Mobile, Fax, Email, LockStatus

Now I want to select LockStatus from this table. In traditional mode we made this query and send it to SqlCommand for execute:

SELECT LockStatus FROM UsersInfo

And today with use Entity Framework, we use this from of query:

var q = from r in new Data_DBEntities().UsersInfo
        select new
        {
           r.LockStatus
        };

Entity SQL:

SELECT UsersInfo.LockStatus
FROM Data_DBEntities.UsersInfo

Now I start the application and trace this it with SQL Server Profiler. If I use the first type of query (traditional mode) I see this result:

SELECT LockStatus FROM UsersInfo

But when I use Entity Framework (LINQ || Entity SQL) the SQL Server Profiler show this result:

SELECT 
[Extent1].[LockStatus] AS [LockStatus]
FROM (SELECT 
      [UsersInfo].[Id] AS [Id], 
      [UsersInfo].[UserName] AS [UserName],
      [UsersInfo].[Password] AS [Password],
      [UsersInfo].[FName] AS [FName],
      [UsersInfo].[LName] AS [LName],
      [UsersInfo].[Gender] AS [Gender],
      [UsersInfo].[Birthday] AS [Birthday],
      [UsersInfo].[HomeTel] AS [HomeTel],
      [UsersInfo].[Mobile] AS [Mobile],
      [UsersInfo].[Fax] AS [Fax],
      [UsersInfo].[Email] AS [Email],
      [UsersInfo].[LockStatus] AS [LockStatus]
      FROM [dbo].[UsersInfo] AS [UsersInfo]) AS [Extent1]

We can see that EF in the background select all of columns.

Now my question is: I just want to select one column, but EF selects all of the columns. If I had 100,000 records in my table, the performance would be really bad!

Maybe say use function or stored procedure, but when you want select different columns in different tables, that's not a good idea.

What do you think? Is there any way?

Was it helpful?

Solution

The query that EF generated has a redundant derived table in it but ultimately it only selects one column. SQL Server, and probably any mainstream RDBMS, only physically touches a single column in this case. Don't worry about performance. This is just cosmetics.

You have done nothing wrong. There's nothing to do for you.

OTHER TIPS

The syntax you used in your LINQ query forced the duplicate selects.

Your projection created 2 separate objects.

var q = from r in new Data_DBEntities().UsersInfo created a new object, and then the

    select new
    {
       r.LockStatus
    };

created a new object based on the first one. You do not need the new keyword in your first section.

if you change the query to be:

var q = from r in Data_DBEntities().UsersInfo
    select new
    {
       r.LockStatus
    }; 

you will get an anonymous projection without an additional object. (And without the additional fields to base the extent on.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top