@@ -68,15 +68,18 @@ 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 isManyToMany ) ;
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 ( ! isManyToMany // many-to-many keys are stored in separate table
79
+ && entityPersister . ColumnsDependOnSubclassJoins ( join . RHSColumns ) )
80
+ {
79
81
return true ;
82
+ }
80
83
}
81
84
82
85
return false ;
@@ -91,14 +94,16 @@ private static SqlString GetTableGroupJoinWithClause(SqlString[] withClauseFragm
91
94
var isAssociationJoin = lhsColumns . Length > 0 ;
92
95
if ( isAssociationJoin )
93
96
{
94
- var entityPersister = GetEntityPersister ( first . Joinable ) ;
97
+ var entityPersister = GetEntityPersister ( first . Joinable , out var isManyToMany ) ;
95
98
string rhsAlias = first . Alias ;
96
99
string [ ] rhsColumns = first . RHSColumns ;
97
100
for ( int j = 0 ; j < lhsColumns . Length ; j ++ )
98
101
{
99
102
fromFragment . Add ( lhsColumns [ j ] )
100
103
. Add ( "=" )
101
- . Add ( entityPersister ? . GenerateTableAliasForColumn ( rhsAlias , rhsColumns [ j ] ) ?? rhsAlias )
104
+ . Add ( ( entityPersister == null || isManyToMany ) // many-to-many keys are stored in separate table
105
+ ? rhsAlias
106
+ : entityPersister . GenerateTableAliasForColumn ( rhsAlias , rhsColumns [ j ] ) )
102
107
. Add ( "." )
103
108
. Add ( rhsColumns [ j ] ) ;
104
109
if ( j != lhsColumns . Length - 1 )
@@ -111,12 +116,14 @@ private static SqlString GetTableGroupJoinWithClause(SqlString[] withClauseFragm
111
116
return fromFragment . ToSqlString ( ) ;
112
117
}
113
118
114
- private static AbstractEntityPersister GetEntityPersister ( IJoinable joinable )
119
+ private static AbstractEntityPersister GetEntityPersister ( IJoinable joinable , out bool isManyToMany )
115
120
{
121
+ isManyToMany = false ;
116
122
if ( ! joinable . IsCollection )
117
123
return joinable as AbstractEntityPersister ;
118
124
119
125
var collection = ( IQueryableCollection ) joinable ;
126
+ isManyToMany = collection . IsManyToMany ;
120
127
return collection . ElementType . IsEntityType ? collection . ElementPersister as AbstractEntityPersister : null ;
121
128
}
122
129
0 commit comments