(From an example in the new Entity Framework book by Julia Lerman.) I have a database with two tables, Contact and Address. The Contact table has a ContactID (int), as well as first name, last name, etc. The Address table has a ContactID, as well as city, state, zip, etc.
Here is a simple LINQ query:
var addressGraphQuery = from a in context.Addresses.Include("Contact")
orderby a.Contact.LastName, a.Contact.FirstName
select a;
From SQL Profiler, I see the following:
SELECT
[Extent1].[addressID] AS [addressID],
[Extent1].[City] AS [City],
[Extent1].[StateProvince] AS [StateProvince],
-- etc
[Extent3].[ContactID] AS [ContactID1],
[Extent3].[FirstName] AS [FirstName],
[Extent3].[LastName] AS [LastName],
-- etc
FROM [dbo].[Address] AS [Extent1]
INNER JOIN [dbo].[Contact] AS [Extent2] ON [Extent1].[ContactID] = [Extent2].[ContactID]
LEFT OUTER JOIN [dbo].[Contact] AS [Extent3] ON [Extent1].[ContactID] = [Extent3].[ContactID]
ORDER BY [Extent2].[LastName] ASC, [Extent3].[FirstName] ASC
It joins against the Contact table twice! Why? Is there an easy way to prevent this?
The mystery deepens. The joins disappear when I remove the orderby's. The joins do not disappear when I set context.ContextOptions.LazyLoadingEnabled = false
.
There is also a similar question here:
Too Many Left Outer Joins in Entity Framework 4?
I'll see if there's a Higher Power I can ask...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…