@@ -68,14 +68,15 @@ private static bool NeedsTableGroupJoin(IReadOnlyList<IJoin> joins, SqlString[]
68
68
69
69
foreach ( var join in joins )
70
70
{
71
- var entityPersister = GetEntityPersister ( join . Joinable ) ;
71
+ var entityPersister = GetEntityPersister ( join . Joinable , out var collection ) ;
72
72
if ( entityPersister ? . HasSubclassJoins ( includeSubclasses && isSubclassIncluded ( join . Alias ) ) != true )
73
73
continue ;
74
74
75
75
if ( hasWithClause )
76
76
return true ;
77
77
78
- if ( entityPersister . ColumnsDependOnSubclassJoins ( join . RHSColumns ) )
78
+ if ( collection ? . IsManyToMany != true // many-to-many keys are stored in separate table
79
+ && entityPersister . ColumnsDependOnSubclassJoins ( join . RHSColumns ) )
79
80
return true ;
80
81
}
81
82
@@ -91,14 +92,16 @@ private static SqlString GetTableGroupJoinWithClause(SqlString[] withClauseFragm
91
92
var isAssociationJoin = lhsColumns . Length > 0 ;
92
93
if ( isAssociationJoin )
93
94
{
94
- var entityPersister = GetEntityPersister ( first . Joinable ) ;
95
+ var entityPersister = GetEntityPersister ( first . Joinable , out var collection ) ;
95
96
string rhsAlias = first . Alias ;
96
97
string [ ] rhsColumns = first . RHSColumns ;
97
98
for ( int j = 0 ; j < lhsColumns . Length ; j ++ )
98
99
{
99
100
fromFragment . Add ( lhsColumns [ j ] )
100
101
. Add ( "=" )
101
- . Add ( entityPersister ? . GenerateTableAliasForColumn ( rhsAlias , rhsColumns [ j ] ) ?? rhsAlias )
102
+ . Add ( entityPersister == null || collection ? . IsManyToMany == true // many-to-many keys are stored in separate table
103
+ ? rhsAlias
104
+ : entityPersister . GenerateTableAliasForColumn ( rhsAlias , rhsColumns [ j ] ) )
102
105
. Add ( "." )
103
106
. Add ( rhsColumns [ j ] ) ;
104
107
if ( j != lhsColumns . Length - 1 )
@@ -111,12 +114,13 @@ private static SqlString GetTableGroupJoinWithClause(SqlString[] withClauseFragm
111
114
return fromFragment . ToSqlString ( ) ;
112
115
}
113
116
114
- private static AbstractEntityPersister GetEntityPersister ( IJoinable joinable )
117
+ private static AbstractEntityPersister GetEntityPersister ( IJoinable joinable , out IQueryableCollection collection )
115
118
{
119
+ collection = null ;
116
120
if ( ! joinable . IsCollection )
117
121
return joinable as AbstractEntityPersister ;
118
122
119
- var collection = ( IQueryableCollection ) joinable ;
123
+ collection = ( IQueryableCollection ) joinable ;
120
124
return collection . ElementType . IsEntityType ? collection . ElementPersister as AbstractEntityPersister : null ;
121
125
}
122
126
0 commit comments