@@ -84,13 +84,19 @@ public virtual async Task<TEntity> GetAndIncludeAsync(TId id, string relationshi
8484
8585 public virtual async Task < TEntity > CreateAsync ( TEntity entity )
8686 {
87- AttachHasManyPointers ( ) ;
87+ AttachRelationships ( ) ;
8888 _dbSet . Add ( entity ) ;
8989
9090 await _context . SaveChangesAsync ( ) ;
9191 return entity ;
9292 }
9393
94+ protected virtual void AttachRelationships ( )
95+ {
96+ AttachHasManyPointers ( ) ;
97+ AttachHasOnePointers ( ) ;
98+ }
99+
94100 /// <summary>
95101 /// This is used to allow creation of HasMany relationships when the
96102 /// dependent side of the relationship already exists.
@@ -107,6 +113,18 @@ private void AttachHasManyPointers()
107113 }
108114 }
109115
116+ /// <summary>
117+ /// This is used to allow creation of HasOne relationships when the
118+ /// independent side of the relationship already exists.
119+ /// </summary>
120+ private void AttachHasOnePointers ( )
121+ {
122+ var relationships = _jsonApiContext . HasOneRelationshipPointers . Get ( ) ;
123+ foreach ( var relationship in relationships )
124+ if ( _context . Entry ( relationship . Value ) . State == EntityState . Detached && _context . EntityIsTracked ( relationship . Value ) == false )
125+ _context . Entry ( relationship . Value ) . State = EntityState . Unchanged ;
126+ }
127+
110128 public virtual async Task < TEntity > UpdateAsync ( TId id , TEntity entity )
111129 {
112130 var oldEntity = await GetAsync ( id ) ;
@@ -185,17 +203,23 @@ public virtual async Task<IEnumerable<TEntity>> PageAsync(IQueryable<TEntity> en
185203
186204 public async Task < int > CountAsync ( IQueryable < TEntity > entities )
187205 {
188- return await entities . CountAsync ( ) ;
206+ return ( entities is IAsyncEnumerable < TEntity > )
207+ ? await entities . CountAsync ( )
208+ : entities . Count ( ) ;
189209 }
190210
191- public Task < TEntity > FirstOrDefaultAsync ( IQueryable < TEntity > entities )
211+ public async Task < TEntity > FirstOrDefaultAsync ( IQueryable < TEntity > entities )
192212 {
193- return entities . FirstOrDefaultAsync ( ) ;
213+ return ( entities is IAsyncEnumerable < TEntity > )
214+ ? await entities . FirstOrDefaultAsync ( )
215+ : entities . FirstOrDefault ( ) ;
194216 }
195217
196218 public async Task < IReadOnlyList < TEntity > > ToListAsync ( IQueryable < TEntity > entities )
197219 {
198- return await entities . ToListAsync ( ) ;
220+ return ( entities is IAsyncEnumerable < TEntity > )
221+ ? await entities . ToListAsync ( )
222+ : entities . ToList ( ) ;
199223 }
200224 }
201225}
0 commit comments