Skip to content

Commit ed2b2d9

Browse files
committed
chore: improved readability CheckForSelfReferingUpdate, comments
1 parent c564f41 commit ed2b2d9

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

src/JsonApiDotNetCore/Data/DefaultEntityRepository.cs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -339,12 +339,20 @@ public virtual async Task<TEntity> UpdateAsync(TId id, TEntity entity)
339339
return oldEntity;
340340
}
341341

342+
/// <summary>
343+
/// In case a relationship is updated where the parent type and related
344+
/// are equal, we need to make sure we don't reattach the parent entity
345+
/// as this will cause entity tracking errors.
346+
/// </summary>
347+
/// <returns>The interpolated related entity collection</returns>
348+
/// <param name="relatedEntities">Related entities.</param>
349+
/// <param name="oldEntity">Old entity.</param>
342350
object CheckForSelfReferingUpdate(IEnumerable<object> relatedEntities, TEntity oldEntity)
343351
{
344-
var entity = relatedEntities.FirstOrDefault();
352+
var relatedType = TypeHelper.GetTypeOfList(relatedEntities.GetType());
345353
var list = new List<TEntity>();
346354
bool refersSelf = false;
347-
if (entity?.GetType() == typeof(TEntity))
355+
if (relatedType == typeof(TEntity))
348356
{
349357
foreach (TEntity e in relatedEntities)
350358
{
@@ -359,7 +367,7 @@ object CheckForSelfReferingUpdate(IEnumerable<object> relatedEntities, TEntity o
359367
}
360368
}
361369
}
362-
return (refersSelf ? list : relatedEntities);
370+
return refersSelf ? list : relatedEntities;
363371

364372
}
365373

src/JsonApiDotNetCore/Internal/TypeHelper.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,15 @@ public static T ConvertType<T>(object value)
6565
return (T)ConvertType(value, typeof(T));
6666
}
6767

68+
public static Type GetTypeOfList(Type type)
69+
{
70+
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
71+
{
72+
return type.GetGenericArguments()[0];
73+
}
74+
return null;
75+
}
76+
6877
/// <summary>
6978
/// Convert collection of query string params to Collection of concrete Type
7079
/// </summary>

0 commit comments

Comments
 (0)