Skip to content

Commit 22a7248

Browse files
committed
first pass at setting relationship Id on POST
1 parent cc80af9 commit 22a7248

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

JsonApiDotNetCore/Abstractions/ModelAccessor.cs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Reflection;
55
using JsonApiDotNetCore.Extensions;
66
using JsonApiDotNetCore.JsonApi;
7+
using Newtonsoft.Json.Linq;
78

89
namespace JsonApiDotNetCore.Abstractions
910
{
@@ -21,7 +22,7 @@ public static Type GetTypeFromModelRelationshipName(Type modelType, string relat
2122
return relationshipType;
2223
}
2324

24-
public static object SetValuesOnModelInstance(object model, Dictionary<string, object> jsonApiAttributes)
25+
public static object SetValuesOnModelInstance(object model, Dictionary<string, object> jsonApiAttributes, Dictionary<string, object> jsonApiRelationships)
2526
{
2627
var modelProperties = model.GetType().GetProperties().ToList();
2728
foreach (var attribute in jsonApiAttributes)
@@ -35,6 +36,23 @@ public static object SetValuesOnModelInstance(object model, Dictionary<string, o
3536
}
3637
});
3738
}
39+
40+
foreach (var relationship in jsonApiRelationships)
41+
{
42+
var relationshipName = relationship.Key;
43+
var relationshipId = ((JObject) relationship.Value)["data"]["id"];
44+
var relationshipPropertyName = $"{relationshipName}Id";
45+
46+
modelProperties.ForEach(pI =>
47+
{
48+
if (pI.Name.ToProperCase() == relationshipPropertyName.ToProperCase())
49+
{
50+
var convertedValue = Convert.ChangeType(relationshipId, pI.PropertyType);
51+
pI.SetValue(model, convertedValue);
52+
}
53+
});
54+
}
55+
3856
return model;
3957
}
4058
}

JsonApiDotNetCore/Services/JsonApiDeserializer.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,10 @@ public object GetEntityFromRequest()
2121
var body = GetRequestBody(_context.HttpContext.Request.Body);
2222
var document = JsonConvert.DeserializeObject<JsonApiDocument>(body);
2323
var entity = Activator.CreateInstance(_context.GetEntityType());
24-
return ModelAccessor.SetValuesOnModelInstance(entity, ((JsonApiDatum)((JObject)document.Data).ToObject(typeof(JsonApiDatum))).Attributes);
24+
var datum = ((JsonApiDatum) ((JObject) document.Data).ToObject(typeof(JsonApiDatum)));
25+
var attributes = datum.Attributes;
26+
var relationships = datum.Relationships;
27+
return ModelAccessor.SetValuesOnModelInstance(entity, attributes, relationships);
2528
}
2629

2730
private static string GetRequestBody(Stream body)

0 commit comments

Comments
 (0)