-
-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy pathHasOneAttribute.cs
More file actions
97 lines (82 loc) · 2.72 KB
/
HasOneAttribute.cs
File metadata and controls
97 lines (82 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using JetBrains.Annotations;
// ReSharper disable NonReadonlyMemberInGetHashCode
namespace JsonApiDotNetCore.Resources.Annotations;
/// <summary>
/// Used to expose a property on a resource class as a JSON:API to-one relationship (https://jsonapi.org/format/#document-resource-object-relationships).
/// </summary>
/// <example>
/// <code><![CDATA[
/// public class Article : Identifiable<long>
/// {
/// [HasOne]
/// public Author Author { get; set; }
/// }
/// ]]></code>
/// </example>
[PublicAPI]
[AttributeUsage(AttributeTargets.Property)]
public sealed class HasOneAttribute : RelationshipAttribute
{
private readonly Lazy<bool> _lazyIsOneToOne;
private HasOneCapabilities? _capabilities;
/// <summary>
/// Inspects <see cref="RelationshipAttribute.InverseNavigationProperty" /> to determine if this is a one-to-one relationship.
/// </summary>
internal bool IsOneToOne => _lazyIsOneToOne.Value;
internal bool HasExplicitCapabilities => _capabilities != null;
/// <summary>
/// The set of allowed capabilities on this to-one relationship. When not explicitly set, the configured default set of capabilities is used.
/// </summary>
/// <example>
/// <code><![CDATA[
/// public class Book : Identifiable<long>
/// {
/// [HasOne(Capabilities = HasOneCapabilities.AllowView | HasOneCapabilities.AllowInclude)]
/// public Person? Author { get; set; }
/// }
/// ]]></code>
/// </example>
public HasOneCapabilities Capabilities
{
get => _capabilities ?? default;
set => _capabilities = value;
}
public HasOneAttribute()
{
_lazyIsOneToOne = new Lazy<bool>(EvaluateIsOneToOne, LazyThreadSafetyMode.PublicationOnly);
}
private bool EvaluateIsOneToOne()
{
if (InverseNavigationProperty != null)
{
Type? elementType = CollectionConverter.Instance.FindCollectionElementType(InverseNavigationProperty.PropertyType);
return elementType == null;
}
return false;
}
/// <inheritdoc />
public override void SetValue(object resource, object? newValue)
{
AssertIsIdentifiable(newValue);
base.SetValue(resource, newValue);
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj is null || GetType() != obj.GetType())
{
return false;
}
var other = (HasOneAttribute)obj;
return _capabilities == other._capabilities && base.Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
return HashCode.Combine(_capabilities, base.GetHashCode());
}
}