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.
Edit
You are using
from pe in proj.ProjectEmailswhereproj.ProjectEmailsis of IEnumerable type. So this LINQ query becomes a LINQ-to-objects query. That is why it loads all the Emails incontext.Emails. Try