|
| 1 | +using System; |
| 2 | +using JsonApiDotNetCore.Data; |
| 3 | +using JsonApiDotNetCore.Models; |
| 4 | +using Microsoft.EntityFrameworkCore; |
| 5 | +using Microsoft.EntityFrameworkCore.Metadata; |
| 6 | + |
| 7 | +namespace JsonApiDotNetCore.Internal |
| 8 | +{ |
| 9 | + /// <summary> |
| 10 | + /// Responsible for populating the RelationshipAttribute InverseNavigation property. |
| 11 | + /// |
| 12 | + /// This service is instantiated in the configure phase of the application. |
| 13 | + /// |
| 14 | + /// When using a data access layer different from EF Core, and when using ResourceHooks |
| 15 | + /// that depend on the inverse navigation property (BeforeImplicitUpdateRelationship), |
| 16 | + /// you will need to override this service, or pass along the inverseNavigationProperty in |
| 17 | + /// the RelationshipAttribute. |
| 18 | + /// </summary> |
| 19 | + public interface IInverseRelationships |
| 20 | + { |
| 21 | + void Resolve(); |
| 22 | + } |
| 23 | + |
| 24 | + public class InverseRelationships : IInverseRelationships |
| 25 | + { |
| 26 | + private readonly ResourceGraph _graph; |
| 27 | + private readonly IDbContextResolver _resolver; |
| 28 | + |
| 29 | + public InverseRelationships(IResourceGraph graph, IDbContextResolver resolver = null) |
| 30 | + { |
| 31 | + _graph = (ResourceGraph)graph; |
| 32 | + _resolver = resolver; |
| 33 | + } |
| 34 | + |
| 35 | + public void Resolve() |
| 36 | + { |
| 37 | + if (EntityFrameworkCoreIsEnabled()) |
| 38 | + { |
| 39 | + DbContext context = _resolver.GetContext(); |
| 40 | + |
| 41 | + foreach (ContextEntity ce in _graph.Entities) |
| 42 | + { |
| 43 | + IEntityType meta = context.Model.FindEntityType(ce.EntityType); |
| 44 | + if (meta == null) continue; |
| 45 | + foreach (var attr in ce.Relationships) |
| 46 | + { |
| 47 | + if (attr is HasManyThroughAttribute) continue; |
| 48 | + INavigation inverseNavigation = meta.FindNavigation(attr.InternalRelationshipName)?.FindInverse(); |
| 49 | + attr.InverseNavigation = inverseNavigation?.Name; |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + /// <summary> |
| 56 | + /// If EF Core is not being used, we're expecting the resolver to not be registered. |
| 57 | + /// </summary> |
| 58 | + /// <returns><c>true</c>, if entity framework core was enabled, <c>false</c> otherwise.</returns> |
| 59 | + /// <param name="resolver">Resolver.</param> |
| 60 | + private bool EntityFrameworkCoreIsEnabled() |
| 61 | + { |
| 62 | + return _resolver != null; |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments