Skip to content

Commit f0d5924

Browse files
committed
fix: foreignkey set null bug
1 parent 0296eb4 commit f0d5924

File tree

2 files changed

+8
-5
lines changed

2 files changed

+8
-5
lines changed

src/JsonApiDotNetCore/Data/DefaultEntityRepository.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -404,8 +404,8 @@ protected void LoadCurrentRelationships(TEntity oldEntity)
404404
/// <summary>
405405
/// assigns relationships that were set in the request to the target entity of the request
406406
/// todo: partially remove dependency on IJsonApiContext here: it is fine to
407-
/// retrieve from the context WHICH relationships to update, but the actual values should
408-
/// come from the context.
407+
/// retrieve from the context WHICH relationships to update, but the actual
408+
/// values should not come from the context.
409409
/// </summary>
410410
protected void AssignRelationshipValues(TEntity oldEntity)
411411
{

src/JsonApiDotNetCore/Models/HasOneAttribute.cs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,13 @@ public HasOneAttribute(string publicName = null, Link documentLinks = Link.All,
5050
/// <param name="newValue">The new property value</param>
5151
public override void SetValue(object resource, object newValue)
5252
{
53-
var propertyInfo = resource
54-
.GetType()
55-
.GetProperty(InternalRelationshipName);
53+
string propertyName = InternalRelationshipName;
54+
// if we're deleting the relationship (setting it to null),
55+
// we set the foreignKey to null. We could also set the actual property to null,
56+
// but then we would first need to load the current relationship, which requires an extra query.
57+
if (newValue == null) propertyName = IdentifiablePropertyName;
5658

59+
var propertyInfo = resource.GetType().GetProperty(propertyName);
5760
propertyInfo.SetValue(resource, newValue);
5861
}
5962

0 commit comments

Comments
 (0)