Skip to content

Commit dae04a1

Browse files
committed
fix(JsonApiDeSerializer): null refs
1 parent 6741efd commit dae04a1

File tree

2 files changed

+12
-11
lines changed

2 files changed

+12
-11
lines changed

src/JsonApiDotNetCore/Serialization/JsonApiDeSerializer.cs

+12-9
Original file line numberDiff line numberDiff line change
@@ -209,20 +209,23 @@ private object SetHasOneRelationship(object entity,
209209

210210
var foreignKey = attr.IdentifiablePropertyName;
211211
var entityProperty = entityProperties.FirstOrDefault(p => p.Name == foreignKey);
212-
if (entityProperty == null)
212+
if (entityProperty == null && rio != null)
213213
throw new JsonApiException(400, $"{contextEntity.EntityType.Name} does not contain a foreign key property '{foreignKey}' for has one relationship '{attr.InternalRelationshipName}'");
214214

215-
// e.g. PATCH /articles
216-
// {... { "relationships":{ "Owner": { "data" :null } } } }
217-
if (rio == null && Nullable.GetUnderlyingType(entityProperty.PropertyType) == null)
218-
throw new JsonApiException(400, $"Cannot set required relationship identifier '{attr.IdentifiablePropertyName}' to null.");
215+
if (entityProperty != null)
216+
{
217+
// e.g. PATCH /articles
218+
// {... { "relationships":{ "Owner": { "data" :null } } } }
219+
if (rio == null && Nullable.GetUnderlyingType(entityProperty.PropertyType) == null)
220+
throw new JsonApiException(400, $"Cannot set required relationship identifier '{attr.IdentifiablePropertyName}' to null.");
219221

220-
var newValue = rio?.Id ?? null;
221-
var convertedValue = TypeHelper.ConvertType(newValue, entityProperty.PropertyType);
222+
var newValue = rio?.Id ?? null;
223+
var convertedValue = TypeHelper.ConvertType(newValue, entityProperty.PropertyType);
222224

223-
_jsonApiContext.RelationshipsToUpdate[relationshipAttr] = convertedValue;
225+
_jsonApiContext.RelationshipsToUpdate[relationshipAttr] = convertedValue;
224226

225-
entityProperty.SetValue(entity, convertedValue);
227+
entityProperty.SetValue(entity, convertedValue);
228+
}
226229
}
227230

228231
return entity;

test/UnitTests/Serialization/JsonApiDeSerializerTests.cs

-2
Original file line numberDiff line numberDiff line change
@@ -345,8 +345,6 @@ private class Dependent : Identifiable
345345
public int IndependentId { get; set; }
346346
}
347347

348-
349-
350348
[Fact]
351349
public void Can_Deserialize_Object_With_HasManyRelationship()
352350
{

0 commit comments

Comments
 (0)