AutoMapper: Projecting Complex Models in Entity Framework Causes Join Duplication

As 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.

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 15 (8 by maintainers)

Most upvoted comments

Looks like EF 6.1.2 has fixed the issue, or at the very least improved the query in some cases.