Projecting Complex Models in Entity Framework Causes Join Duplication
See original GitHub issueAs described in this stack overflow question and its answer, trying to map an EF entity class along with relationships results in unnecessary extra join clauses created for each related field mapped.
for example:
from entity in dbSet
select new { entity.Relationship.Field1, entity.Relationship.Field2 }
might generate the following sql:
SELECT [Extent2].[Field1], [Extent3].[Field2]
FROM EntityTable AS [Extent1]
JOIN RelatedTable AS [Extent2] ON [Extent1].[RelationshipID] = [Extent2].[ID]
JOIN RelatedTable AS [Extent3] ON [Extent1].[RelationshipID] = [Extent3].[ID]
Essentially, every time entity.Relationship
is referenced, a new join will be generated.
Admittedly, this is potentially a shortcoming with Entity Framework. However, I suspect they generate the extra joins because the way the query breaks down into function expressions prevents them from knowing when two usages of entity.Relationship
are really the same join.
I can manually code around this when I’m writing my own queries, but when using AutoMapper’s ProjectTo I don’t have the ability. Since a projection would be able to re-use the join, I’m hoping this can be worked around in AutoMapper, too.
Issue Analytics
- State:
- Created 9 years ago
- Comments:15 (8 by maintainers)
Top GitHub Comments
Looks like EF 6.1.2 has fixed the issue, or at the very least improved the query in some cases.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.