简体   繁体   中英

Entity framework is generating SQL that returns the entire table

When I try to join a few tables the entity framework seems to be returning the entire table. As this table is quite large I need it to only return the rows needed.

I have three tables:

Project       - ProjectID, ProjectName
ProjectEmail  - ProjectEmailID, ProjectID, EmailID, RemovedFlag, CreatedBy
Email         - EmailID, Subject, Body 

I am trying to retrieve Email data for a particular Project. When I do this:

using (DatabaseEntities context = new DatabaseEntities())
{
    Project proj = context.Projects.Where(p => p.ProjectID == ProjectID).FirstOrDefault();
    if (proj != null)
    {
        List<Email> projectEmails = (from pe in proj.ProjectEmails
                                     join e in context.Emails on pe.EmailID equals e.EmailID
                                     select e).ToList();
    }

}

The SQL that is generated is this:

exec sp_executesql N'SELECT TOP (1) 
[Extent1].[ProjectID] AS [ProjectID], 
[Extent1].[ProjectName] AS [ProjectName],
    -- rest of columns appear here 
FROM [dbo].[Project] AS [Extent1]
WHERE [Extent1].[ProjectID] = @p__linq__0',N'@p__linq__0 int',@p__linq__0=6

excellent, except that the second query generates this:

SELECT  [Extent1].[EmailID] AS [EmailID], 
    [Extent1].[Subject] AS [Subject],
            -- rest of columns appear here
FROM [dbo].[Email] AS [Extent1]

Email is a big table and I really don't want to be pulling back the entire table! Is there a better way to return the list if Emails so that the table joins on the correct keys?

I am also confused how it knows which Emails to return, because I can't see the first or second query joining on the ProjectEmail table.

You missed the where condition in the query.

List<Email> projectEmails = (from pe in proj.ProjectEmails
                             join e in context.Emails on pe.EmailID equals e.EmailID
                             where pe.ProjectID == proj.ProjectID
                             select e).ToList();

Edit

You are using from pe in proj.ProjectEmails where proj.ProjectEmails is of IEnumerable type. So this LINQ query becomes a LINQ-to-objects query. That is why it loads all the Emails in context.Emails . Try

List<Email> projectEmails = (from pe in context.ProjectEmails
                            join e in context.Emails on pe.EmailID equals e.EmailID
                            where pe.ProjectID == proj.ProjectID
                            select e).ToList();

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