Skip to content

Commit 02d19b5

Browse files
committed
Adapts marking many-to-many relationships as tracked so it no longer needs the Issue26779 EF Core back-compat switch. The switch is unavailable in EF 7, so this change unblocks us from upgrade.
1 parent 0185311 commit 02d19b5

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

src/JsonApiDotNetCore/Configuration/JsonApiOptions.cs

-6
Original file line numberDiff line numberDiff line change
@@ -102,12 +102,6 @@ public sealed class JsonApiOptions : IJsonApiOptions
102102
}
103103
};
104104

105-
static JsonApiOptions()
106-
{
107-
// Bug workaround for https://github.com/dotnet/efcore/issues/27436
108-
AppContext.SetSwitch("Microsoft.EntityFrameworkCore.Issue26779", true);
109-
}
110-
111105
public JsonApiOptions()
112106
{
113107
_lazySerializerReadOptions = new Lazy<JsonSerializerOptions>(() => new JsonSerializerOptions(SerializerOptions), LazyThreadSafetyMode.PublicationOnly);

src/JsonApiDotNetCore/Repositories/EntityFrameworkCoreRepository.cs

+28
Original file line numberDiff line numberDiff line change
@@ -547,6 +547,34 @@ private void MarkRelationshipAsLoaded(TResource leftResource, RelationshipAttrib
547547
EntityEntry<TResource> leftEntry = _dbContext.Entry(leftResource);
548548
CollectionEntry rightCollectionEntry = leftEntry.Collection(relationship.Property.Name);
549549
rightCollectionEntry.IsLoaded = true;
550+
551+
if (rightCollectionEntry.Metadata is ISkipNavigation skipNavigation)
552+
{
553+
MarkManyToManyRelationshipAsLoaded(leftEntry, skipNavigation);
554+
}
555+
}
556+
557+
private void MarkManyToManyRelationshipAsLoaded(EntityEntry<TResource> leftEntry, ISkipNavigation skipNavigation)
558+
{
559+
string[] primaryKeyNames = skipNavigation.ForeignKey.PrincipalKey.Properties.Select(property => property.Name).ToArray();
560+
object?[] primaryKeyValues = GetCurrentKeyValues(leftEntry, primaryKeyNames);
561+
562+
string[] foreignKeyNames = skipNavigation.ForeignKey.Properties.Select(property => property.Name).ToArray();
563+
564+
foreach (EntityEntry joinEntry in _dbContext.ChangeTracker.Entries().Where(entry => entry.Metadata == skipNavigation.JoinEntityType).ToList())
565+
{
566+
object?[] foreignKeyValues = GetCurrentKeyValues(joinEntry, foreignKeyNames);
567+
568+
if (primaryKeyValues.SequenceEqual(foreignKeyValues))
569+
{
570+
joinEntry.State = EntityState.Unchanged;
571+
}
572+
}
573+
}
574+
575+
private static object?[] GetCurrentKeyValues(EntityEntry entry, IEnumerable<string> keyNames)
576+
{
577+
return keyNames.Select(keyName => entry.Property(keyName).CurrentValue).ToArray();
550578
}
551579

552580
protected async Task UpdateRelationshipAsync(RelationshipAttribute relationship, TResource leftResource, object? valueToAssign,

0 commit comments

Comments
 (0)