Skip to content

Use reference equality to compare model instances in EditContext #18172

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions src/Components/Forms/src/FieldIdentifier.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;

namespace Microsoft.AspNetCore.Components.Forms
{
Expand Down Expand Up @@ -35,7 +36,7 @@ public static FieldIdentifier Create<TField>(Expression<Func<TField>> accessor)
/// <param name="fieldName">The name of the editable field.</param>
public FieldIdentifier(object model, string fieldName)
{
if (model == null)
if (model is null)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In case a user type has a poorly implemented equality operator.

{
throw new ArgumentNullException(nameof(model));
}
Expand Down Expand Up @@ -64,7 +65,16 @@ public FieldIdentifier(object model, string fieldName)

/// <inheritdoc />
public override int GetHashCode()
=> (Model, FieldName).GetHashCode();
{
// We want to compare Model instances by reference. RuntimeHelpers.GetHashCode returns identical hashes for equal object references (ignoring any `Equals`/`GetHashCode` overrides) which is what we want.
var modelHash = RuntimeHelpers.GetHashCode(Model);
var fieldHash = StringComparer.Ordinal.GetHashCode(FieldName);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed to use the same Comparer used by Equals

return (
modelHash,
fieldHash
)
.GetHashCode();
}

/// <inheritdoc />
public override bool Equals(object obj)
Expand All @@ -75,7 +85,7 @@ public override bool Equals(object obj)
public bool Equals(FieldIdentifier otherIdentifier)
{
return
otherIdentifier.Model == Model &&
ReferenceEquals(otherIdentifier.Model, Model) &&
string.Equals(otherIdentifier.FieldName, FieldName, StringComparison.Ordinal);
}

Expand Down
30 changes: 30 additions & 0 deletions src/Components/Forms/test/EditContextTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -236,5 +236,35 @@ public void RequestsValidationWhenValidateIsCalled()
Assert.False(isValid);
Assert.Equal(new[] { "Some message" }, editContext.GetValidationMessages());
}

[Fact]
public void LookingUpModel_ThatOverridesGetHashCodeAndEquals_Works()
{
// Test for https://github.com/aspnet/AspNetCore/issues/18069
// Arrange
var model = new EquatableModel();
var editContext = new EditContext(model);

editContext.NotifyFieldChanged(editContext.Field(nameof(EquatableModel.Property)));

model.Property = "new value";

Assert.True(editContext.IsModified(editContext.Field(nameof(EquatableModel.Property))));
}

class EquatableModel : IEquatable<EquatableModel>
{
public string Property { get; set; } = "";

public bool Equals(EquatableModel other)
{
return string.Equals(Property, other?.Property, StringComparison.Ordinal);
}

public override int GetHashCode()
{
return StringComparer.Ordinal.GetHashCode(Property);
}
}
}
}
42 changes: 42 additions & 0 deletions src/Components/Forms/test/FieldIdentifierTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,19 @@ public void DistinctFieldNamesProduceDistinctHashCodesAndNonEquality()
Assert.False(fieldIdentifier1.Equals(fieldIdentifier2));
}

[Fact]
public void FieldIdentifier_ForModelWithoutField_ProduceSameHashCodesAndEquality()
{
// Arrange
var model = new object();
var fieldIdentifier1 = new FieldIdentifier(model, fieldName: string.Empty);
var fieldIdentifier2 = new FieldIdentifier(model, fieldName: string.Empty);

// Act/Assert
Assert.Equal(fieldIdentifier1.GetHashCode(), fieldIdentifier2.GetHashCode());
Assert.True(fieldIdentifier1.Equals(fieldIdentifier2));
}

[Fact]
public void SameContentsProduceSameHashCodesAndEquality()
{
Expand All @@ -89,6 +102,20 @@ public void SameContentsProduceSameHashCodesAndEquality()
Assert.True(fieldIdentifier1.Equals(fieldIdentifier2));
}

[Fact]
public void SameContents_WithOverridenEqualsAndGetHashCode_ProduceSameHashCodesAndEquality()
{
// Arrange
var model = new EquatableModel();
var fieldIdentifier1 = new FieldIdentifier(model, nameof(EquatableModel.Property));
model.Property = "changed value"; // To show it makes no difference if the overridden `GetHashCode` result changes
var fieldIdentifier2 = new FieldIdentifier(model, nameof(EquatableModel.Property));

// Act/Assert
Assert.Equal(fieldIdentifier1.GetHashCode(), fieldIdentifier2.GetHashCode());
Assert.True(fieldIdentifier1.Equals(fieldIdentifier2));
}

[Fact]
public void FieldNamesAreCaseSensitive()
{
Expand Down Expand Up @@ -194,5 +221,20 @@ class ParentModel
{
public TestModel Child { get; set; }
}

class EquatableModel : IEquatable<EquatableModel>
{
public string Property { get; set; } = "";

public bool Equals(EquatableModel other)
{
return string.Equals(Property, other?.Property, StringComparison.Ordinal);
}

public override int GetHashCode()
{
return StringComparer.Ordinal.GetHashCode(Property);
}
}
}
}