Skip to content

Commit

Permalink
Allow dependents that can match a principal through multiple relation…
Browse files Browse the repository at this point in the history
…ships

Fixes #12227

This issues happens when the principal side of multiple relationships is using inheritance and the relationships share and FK property and principal key definition. In this case, the FK value may match instances that are not of the correct type for the given relationship. This would normally be an error and we started throwing for it in 2.1. But it is not an error if the principal is correct for some other relationship sharing the same FK property. So the fix here is to check all the FKs to see if any one can be used. If so, then no problem. If not, then still an error to catch the common case. No matches is also okay, since we don't know whether the principal is loaded or not.

Note that technically, GetPrincipal is broken and should be fixed with new API surface to get all possible principals, but not doing this here because it would be new API in a patch.
  • Loading branch information
ajcvickers committed Jul 5, 2018
1 parent fac2ede commit 312d7da
Show file tree
Hide file tree
Showing 3 changed files with 196 additions and 20 deletions.
62 changes: 62 additions & 0 deletions src/EFCore.Specification.Tests/GraphUpdatesFixtureBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,20 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con

modelBuilder.Entity<BadCustomer>();
modelBuilder.Entity<BadOrder>();

modelBuilder.Entity<QuestTask>();

modelBuilder.Entity<QuizTask>()
.HasMany(qt => qt.Choices)
.WithOne()
.HasForeignKey(tc => tc.QuestTaskId);

modelBuilder.Entity<HiddenAreaTask>()
.HasMany(hat => hat.Choices)
.WithOne()
.HasForeignKey(tc => tc.QuestTaskId);

modelBuilder.Entity<TaskChoice>();
}

protected virtual object CreateFullGraph()
Expand Down Expand Up @@ -2548,6 +2562,54 @@ public BadCustomer BadCustomer
}
}

protected class HiddenAreaTask : TaskWithChoices
{
}

protected abstract class QuestTask : NotifyingEntity
{
private int _id;

public int Id
{
get => _id;
set => SetWithNotify(value, ref _id);
}
}

protected class QuizTask : TaskWithChoices
{
}

protected class TaskChoice : NotifyingEntity
{
private int _id;
private int _questTaskId;

public int Id
{
get => _id;
set => SetWithNotify(value, ref _id);
}

public int QuestTaskId
{
get => _questTaskId;
set => SetWithNotify(value, ref _questTaskId);
}
}

protected abstract class TaskWithChoices : QuestTask
{
private ICollection<TaskChoice> _choices = new ObservableHashSet<TaskChoice>(ReferenceEqualityComparer.Instance);

public ICollection<TaskChoice> Choices
{
get => _choices;
set => SetWithNotify(value, ref _choices);
}
}

protected class NotifyingEntity : INotifyPropertyChanging, INotifyPropertyChanged
{
protected void SetWithNotify<T>(T value, ref T field, [CallerMemberName] string propertyName = "")
Expand Down
97 changes: 97 additions & 0 deletions src/EFCore.Specification.Tests/GraphUpdatesTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5733,5 +5733,102 @@ public virtual void Sometimes_not_calling_DetectChanges_when_required_does_not_t
Assert.Empty(principal.BadOrders);
});
}

[ConditionalFact]
public virtual void Can_add_valid_first_depedent_when_multiple_possible_principal_sides()
{
ExecuteWithStrategyInTransaction(
context =>
{
var quizTask = new QuizTask();
quizTask.Choices.Add(new TaskChoice());

context.Add(quizTask);

context.SaveChanges();
},
context =>
{
var quizTask = context.Set<QuizTask>().Include(e => e.Choices).Single();

Assert.Equal(quizTask.Id, quizTask.Choices.Single().QuestTaskId);

Assert.Same(quizTask.Choices.Single(), context.Set<TaskChoice>().Single());

Assert.Empty(context.Set<HiddenAreaTask>().Include(e => e.Choices));
});
}

[ConditionalFact]
public virtual void Can_add_valid_second_depedent_when_multiple_possible_principal_sides()
{
ExecuteWithStrategyInTransaction(
context =>
{
var hiddenAreaTask = new HiddenAreaTask();
hiddenAreaTask.Choices.Add(new TaskChoice());

context.Add(hiddenAreaTask);

context.SaveChanges();
},
context =>
{
var hiddenAreaTask = context.Set<HiddenAreaTask>().Include(e => e.Choices).Single();

Assert.Equal(hiddenAreaTask.Id, hiddenAreaTask.Choices.Single().QuestTaskId);

Assert.Same(hiddenAreaTask.Choices.Single(), context.Set<TaskChoice>().Single());

Assert.Empty(context.Set<QuizTask>().Include(e => e.Choices));
});
}

[ConditionalFact]
public virtual void Can_add_multiple_depedents_when_multiple_possible_principal_sides()
{
ExecuteWithStrategyInTransaction(
context =>
{
var quizTask = new QuizTask();
quizTask.Choices.Add(new TaskChoice());
quizTask.Choices.Add(new TaskChoice());

context.Add(quizTask);

var hiddenAreaTask = new HiddenAreaTask();
hiddenAreaTask.Choices.Add(new TaskChoice());
hiddenAreaTask.Choices.Add(new TaskChoice());

context.Add(hiddenAreaTask);

context.SaveChanges();
},
context =>
{
var quizTask = context.Set<QuizTask>().Include(e => e.Choices).Single();
var hiddenAreaTask = context.Set<HiddenAreaTask>().Include(e => e.Choices).Single();

Assert.Equal(2, quizTask.Choices.Count);
foreach (var quizTaskChoice in quizTask.Choices)
{
Assert.Equal(quizTask.Id, quizTaskChoice.QuestTaskId);
}

Assert.Equal(2, hiddenAreaTask.Choices.Count);
foreach (var hiddenAreaTaskChoice in hiddenAreaTask.Choices)
{
Assert.Equal(hiddenAreaTask.Id, hiddenAreaTaskChoice.QuestTaskId);
}

foreach (var taskChoice in context.Set<TaskChoice>())
{
Assert.Equal(
1,
quizTask.Choices.Count(e => e.Id == taskChoice.Id)
+ hiddenAreaTask.Choices.Count(e => e.Id == taskChoice.Id));
}
});
}
}
}
57 changes: 37 additions & 20 deletions src/EFCore/ChangeTracking/Internal/NavigationFixer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,8 @@ private void InitialFixup(
{
var entityType = (EntityType)entry.EntityType;
var stateManager = entry.StateManager;
IForeignKey conflictingPrincipalForeignKey = null;
var matchingPrincipal = false;

foreach (var foreignKey in entityType.GetForeignKeys())
{
Expand All @@ -541,32 +543,47 @@ private void InitialFixup(
{
if (!foreignKey.PrincipalEntityType.IsAssignableFrom(principalEntry.EntityType))
{
if (_sensitiveLoggingEnabled)
{
throw new InvalidOperationException(CoreStrings.IncompatiblePrincipalEntrySensitive(
entry.BuildCurrentValuesString(foreignKey.Properties),
entityType.DisplayName(),
entry.BuildOriginalValuesString(entityType.FindPrimaryKey().Properties),
principalEntry.EntityType.DisplayName(),
foreignKey.PrincipalEntityType.DisplayName()));
}

throw new InvalidOperationException(CoreStrings.IncompatiblePrincipalEntry(
Property.Format(foreignKey.Properties),
entityType.DisplayName(),
principalEntry.EntityType.DisplayName(),
foreignKey.PrincipalEntityType.DisplayName()));
conflictingPrincipalForeignKey = foreignKey;
}
else
{
matchingPrincipal = true;

// Set navigation to principal based on FK properties
SetNavigation(entry, foreignKey.DependentToPrincipal, principalEntry);
// Set navigation to principal based on FK properties
SetNavigation(entry, foreignKey.DependentToPrincipal, principalEntry);

// Add this entity to principal's collection, or set inverse for 1:1
ToDependentFixup(entry, principalEntry, foreignKey);
// Add this entity to principal's collection, or set inverse for 1:1
ToDependentFixup(entry, principalEntry, foreignKey);
}
}
}
}

if (!matchingPrincipal
&& conflictingPrincipalForeignKey != null)
{
var principalEntry = stateManager.GetPrincipal(entry, conflictingPrincipalForeignKey);

if (_sensitiveLoggingEnabled)
{
throw new InvalidOperationException(
CoreStrings.IncompatiblePrincipalEntrySensitive(
entry.BuildCurrentValuesString(conflictingPrincipalForeignKey.Properties),
entityType.DisplayName(),
entry.BuildOriginalValuesString(entityType.FindPrimaryKey().Properties),
principalEntry.EntityType.DisplayName(),
conflictingPrincipalForeignKey.PrincipalEntityType.DisplayName()));
}

throw new InvalidOperationException(
CoreStrings.IncompatiblePrincipalEntry(
Property.Format(conflictingPrincipalForeignKey.Properties),
entityType.DisplayName(),
principalEntry.EntityType.DisplayName(),
conflictingPrincipalForeignKey.PrincipalEntityType.DisplayName()));
}


foreach (var foreignKey in entityType.GetReferencingForeignKeys())
{
if (handledForeignKeys == null
Expand Down Expand Up @@ -829,7 +846,7 @@ private void ConditionallyNullForeignKeyProperties(
for (var i = 0; i < foreignKey.Properties.Count; i++)
{
if (!PrincipalValueEqualsDependentValue(
principalProperties[i],
principalProperties[i],
dependentEntry[dependentProperties[i]],
principalEntry[principalProperties[i]]))
{
Expand Down

0 comments on commit 312d7da

Please sign in to comment.