33using System . Linq ;
44using System . Reflection ;
55using Microsoft . EntityFrameworkCore ;
6+ using JsonApiDotNetCore . Models ;
67
78namespace JsonApiDotNetCore . Internal
89{
@@ -14,7 +15,6 @@ public class ContextGraphBuilder<T> where T : DbContext
1415 public ContextGraph < T > Build ( )
1516 {
1617 _getFirstLevelEntities ( ) ;
17- _loadRelationships ( ) ;
1818
1919 var graph = new ContextGraph < T >
2020 {
@@ -41,7 +41,8 @@ private void _getFirstLevelEntities()
4141 entities . Add ( new ContextEntity {
4242 EntityName = property . Name ,
4343 EntityType = entityType ,
44- Attributes = _getAttributes ( entityType )
44+ Attributes = _getAttributes ( entityType ) ,
45+ Relationships = _getRelationships ( entityType )
4546 } ) ;
4647 }
4748 }
@@ -65,38 +66,29 @@ private List<AttrAttribute> _getAttributes(Type entityType)
6566 return attributes ;
6667 }
6768
68- private void _loadRelationships ( )
69- {
70- _entities . ForEach ( entity => {
71-
72- var relationships = new List < Relationship > ( ) ;
73- var properties = entity . EntityType . GetProperties ( ) ;
74-
75- foreach ( var entityProperty in properties )
76- {
77- var propertyType = entityProperty . PropertyType ;
78-
79- if ( _isValidEntity ( propertyType )
80- || ( propertyType . GetTypeInfo ( ) . IsGenericType && _isValidEntity ( propertyType . GetGenericArguments ( ) [ 0 ] ) ) )
81- relationships . Add ( _getRelationshipFromPropertyInfo ( entityProperty ) ) ;
82- }
83-
84- entity . Relationships = relationships ;
85- } ) ;
86- }
87-
88- private bool _isValidEntity ( Type type )
69+ private List < RelationshipAttribute > _getRelationships ( Type entityType )
8970 {
90- var validEntityRelationshipTypes = _entities . Select ( e => e . EntityType ) ;
91- return validEntityRelationshipTypes . Contains ( type ) ;
71+ var attributes = new List < RelationshipAttribute > ( ) ;
72+
73+ var properties = entityType . GetProperties ( ) ;
74+
75+ foreach ( var prop in properties )
76+ {
77+ var attribute = ( RelationshipAttribute ) prop . GetCustomAttribute ( typeof ( RelationshipAttribute ) ) ;
78+ if ( attribute == null ) continue ;
79+ attribute . InternalRelationshipName = prop . Name ;
80+ attribute . Type = _getRelationshipType ( attribute , prop ) ;
81+ attributes . Add ( attribute ) ;
82+ }
83+ return attributes ;
9284 }
9385
94- private Relationship _getRelationshipFromPropertyInfo ( PropertyInfo propertyInfo )
86+ private Type _getRelationshipType ( RelationshipAttribute relation , PropertyInfo prop )
9587 {
96- return new Relationship {
97- Type = propertyInfo . PropertyType ,
98- RelationshipName = propertyInfo . Name
99- } ;
88+ if ( relation . IsHasMany )
89+ return prop . PropertyType . GetGenericArguments ( ) [ 0 ] ;
90+ else
91+ return prop . PropertyType ;
10092 }
10193 }
10294}
0 commit comments