Skip to content

Commit 402d6cc

Browse files
committed
feat(relationship-attr): make setValue abstract
allows setting of has-one relationship by Id
1 parent 588b980 commit 402d6cc

File tree

3 files changed

+27
-11
lines changed

3 files changed

+27
-11
lines changed

src/JsonApiDotNetCore/Models/HasManyAttribute.cs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System.Reflection;
22

33
namespace JsonApiDotNetCore.Models
44
{
@@ -9,5 +9,14 @@ public HasManyAttribute(string publicName)
99
{
1010
PublicRelationshipName = publicName;
1111
}
12+
13+
public override void SetValue(object entity, object newValue)
14+
{
15+
var propertyInfo = entity
16+
.GetType()
17+
.GetProperty(InternalRelationshipName);
18+
19+
propertyInfo.SetValue(entity, newValue);
20+
}
1221
}
1322
}

src/JsonApiDotNetCore/Models/HasOneAttribute.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
using System.Reflection;
2+
13
namespace JsonApiDotNetCore.Models
24
{
35
public class HasOneAttribute : RelationshipAttribute
@@ -7,5 +9,18 @@ public HasOneAttribute(string publicName)
79
{
810
PublicRelationshipName = publicName;
911
}
12+
13+
public override void SetValue(object entity, object newValue)
14+
{
15+
var propertyName = (newValue.GetType() == Type)
16+
? InternalRelationshipName
17+
: $"{InternalRelationshipName}Id";
18+
19+
var propertyInfo = entity
20+
.GetType()
21+
.GetProperty(propertyName);
22+
23+
propertyInfo.SetValue(entity, newValue);
24+
}
1025
}
1126
}
Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
using System;
2-
using System.Reflection;
32

43
namespace JsonApiDotNetCore.Models
54
{
6-
public class RelationshipAttribute : Attribute
5+
public abstract class RelationshipAttribute : Attribute
76
{
87
protected RelationshipAttribute(string publicName)
98
{
@@ -16,13 +15,6 @@ protected RelationshipAttribute(string publicName)
1615
public bool IsHasMany { get { return this.GetType() == typeof(HasManyAttribute); } }
1716
public bool IsHasOne { get { return this.GetType() == typeof(HasOneAttribute); } }
1817

19-
public void SetValue(object entity, object newValue)
20-
{
21-
var propertyInfo = entity
22-
.GetType()
23-
.GetProperty(InternalRelationshipName);
24-
25-
propertyInfo.SetValue(entity, newValue);
26-
}
18+
public abstract void SetValue(object entity, object newValue);
2719
}
2820
}

0 commit comments

Comments
 (0)