Skip to content

fix/#445 #446

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Nov 29, 2018
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -234,3 +234,6 @@ _Pvt_Extensions

# FAKE - F# Make
.fake/

### Rider ###
.idea/
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using JsonApiDotNetCore.Models;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using JsonApiDotNetCoreExample.Models.Entities;

namespace JsonApiDotNetCoreExample.Models.Resources
{
Expand All @@ -17,7 +18,7 @@ public class CourseResource : Identifiable
[Attr("description")]
public string Description { get; set; }

[HasOne("department")]
[HasOne("department", withEntity: "Department")]
public DepartmentResource Department { get; set; }
public int? DepartmentId { get; set; }

Expand Down
11 changes: 3 additions & 8 deletions src/JsonApiDotNetCore/Builders/ContextGraphBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ protected virtual List<RelationshipAttribute> GetRelationships(Type entityType)
attribute.Type = GetRelationshipType(attribute, prop);
attributes.Add(attribute);

if(attribute is HasManyThroughAttribute hasManyThroughAttribute) {
if (attribute is HasManyThroughAttribute hasManyThroughAttribute) {
var throughProperty = properties.SingleOrDefault(p => p.Name == hasManyThroughAttribute.InternalThroughName);
if(throughProperty == null)
throw new JsonApiSetupException($"Invalid '{nameof(HasManyThroughAttribute)}' on type '{entityType}'. Type does not contain a property named '{hasManyThroughAttribute.InternalThroughName}'.");
Expand Down Expand Up @@ -211,13 +211,8 @@ protected virtual List<RelationshipAttribute> GetRelationships(Type entityType)
return attributes;
}

protected virtual Type GetRelationshipType(RelationshipAttribute relation, PropertyInfo prop)
{
if (relation.IsHasMany)
return prop.PropertyType.GetGenericArguments()[0];
else
return prop.PropertyType;
}
protected virtual Type GetRelationshipType(RelationshipAttribute relation, PropertyInfo prop) =>
relation.IsHasMany ? prop.PropertyType.GetGenericArguments()[0] : prop.PropertyType;

private Type GetResourceDefinitionType(Type entityType) => typeof(ResourceDefinition<>).MakeGenericType(entityType);

Expand Down
35 changes: 30 additions & 5 deletions src/JsonApiDotNetCore/Data/DefaultEntityRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,15 +155,25 @@ public virtual async Task<TEntity> CreateAsync(TEntity entity)
protected virtual void AttachRelationships(TEntity entity = null)
{
AttachHasManyPointers(entity);
AttachHasOnePointers();
AttachHasOnePointers(entity);
}

/// <inheritdoc />
public void DetachRelationshipPointers(TEntity entity)
{
foreach (var hasOneRelationship in _jsonApiContext.HasOneRelationshipPointers.Get())
{
_context.Entry(hasOneRelationship.Value).State = EntityState.Detached;
var hasOne = (HasOneAttribute) hasOneRelationship.Key;
if (hasOne.EntityPropertyName != null)
{
var relatedEntity = entity.GetType().GetProperty(hasOne.EntityPropertyName)?.GetValue(entity);
if (relatedEntity != null)
_context.Entry(relatedEntity).State = EntityState.Detached;
}
else
{
_context.Entry(hasOneRelationship.Value).State = EntityState.Detached;
}
}

foreach (var hasManyRelationship in _jsonApiContext.HasManyRelationshipPointers.Get())
Expand Down Expand Up @@ -227,12 +237,27 @@ private void AttachHasManyThrough(TEntity entity, HasManyThroughAttribute hasMan
/// This is used to allow creation of HasOne relationships when the
/// independent side of the relationship already exists.
/// </summary>
private void AttachHasOnePointers()
private void AttachHasOnePointers(TEntity entity)
{
var relationships = _jsonApiContext.HasOneRelationshipPointers.Get();
foreach (var relationship in relationships)
if (_context.Entry(relationship.Value).State == EntityState.Detached && _context.EntityIsTracked(relationship.Value) == false)
_context.Entry(relationship.Value).State = EntityState.Unchanged;
{
if (relationship.Key.GetType() != typeof(HasOneAttribute))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Under what circumstances does this happen?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is totally just a guard clause since the dictionary key is RelationshipAttribute.

continue;

var hasOne = (HasOneAttribute) relationship.Key;
if (hasOne.EntityPropertyName != null)
{
var relatedEntity = entity.GetType().GetProperty(hasOne.EntityPropertyName)?.GetValue(entity);
if (relatedEntity != null && _context.Entry(relatedEntity).State == EntityState.Detached && _context.EntityIsTracked((IIdentifiable)relatedEntity) == false)
_context.Entry(relatedEntity).State = EntityState.Unchanged;
}
else
{
if (_context.Entry(relationship.Value).State == EntityState.Detached && _context.EntityIsTracked(relationship.Value) == false)
_context.Entry(relationship.Value).State = EntityState.Unchanged;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's refactor this a bit so it's clearer and we don't have separate definitions for how the EF ChangeTracker entry state is modified. The only thing that needs to be in the conditional is how we determine the relatedEntity. so, maybe something like:

IIdentifiable relatedEntity = (hasOne.EntityPropertyName != null)
    ? entity.GetType().GetProperty(hasOne.EntityPropertyName)?.GetValue(entity) as IIdentifiable
    : relationship.Value;

if(relatedEntity != null 
    && _context.Entry(relatedEntity).State == EntityState.Detached 
    && _context.EntityIsTracked(relatedEntity) == false) {
        _context.Entry(relatedEntity).State = EntityState.Unchanged;
}

}
}
}

/// <inheritdoc />
Expand Down
4 changes: 2 additions & 2 deletions src/JsonApiDotNetCore/Internal/Query/BaseAttrQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ private RelationshipAttribute GetRelationship(string propertyName)

private AttrAttribute GetAttribute(RelationshipAttribute relationship, string attribute)
{
var relatedContextExntity = _jsonApiContext.ResourceGraph.GetContextEntity(relationship.Type);
return relatedContextExntity.Attributes
var relatedContextEntity = _jsonApiContext.ResourceGraph.GetContextEntity(relationship.Type);
return relatedContextEntity.Attributes
.FirstOrDefault(a => a.Is(attribute));
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/JsonApiDotNetCore/JsonApiDotNetCore.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<VersionPrefix>3.0.0</VersionPrefix>
<VersionPrefix>3.0.1</VersionPrefix>
<TargetFrameworks>$(NetStandardVersion)</TargetFrameworks>
<AssemblyName>JsonApiDotNetCore</AssemblyName>
<PackageId>JsonApiDotNetCore</PackageId>
Expand Down
14 changes: 11 additions & 3 deletions src/JsonApiDotNetCore/Models/HasOneAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,35 +13,43 @@ public class HasOneAttribute : RelationshipAttribute
/// <param name="documentLinks">Which links are available. Defaults to <see cref="Link.All"/></param>
/// <param name="canInclude">Whether or not this relationship can be included using the <c>?include=public-name</c> query string</param>
/// <param name="withForeignKey">The foreign key property name. Defaults to <c>"{RelationshipName}Id"</c></param>
/// <param name="withEntity">If the entity model of this relationship refers to a different type, specify that here</param>
///
/// <example>
/// Using an alternative foreign key:
///
/// <code>
/// public class Article : Identifiable
/// {
/// [HasOne("author", withForiegnKey: nameof(AuthorKey)]
/// [HasOne("author", withForeignKey: nameof(AuthorKey)]
/// public Author Author { get; set; }
/// public int AuthorKey { get; set; }
/// }
/// </code>
///
/// </example>
public HasOneAttribute(string publicName = null, Link documentLinks = Link.All, bool canInclude = true, string withForeignKey = null)
public HasOneAttribute(string publicName = null, Link documentLinks = Link.All, bool canInclude = true, string withForeignKey = null, string withEntity = null)
: base(publicName, documentLinks, canInclude)
{
_explicitIdentifiablePropertyName = withForeignKey;
EntityPropertyName = withEntity;
}

private readonly string _explicitIdentifiablePropertyName;

private readonly string _relatedEntityPropertyName;

/// <summary>
/// The independent resource identifier.
/// </summary>
public string IdentifiablePropertyName => string.IsNullOrWhiteSpace(_explicitIdentifiablePropertyName)
? JsonApiOptions.RelatedIdMapper.GetRelatedIdPropertyName(InternalRelationshipName)
: _explicitIdentifiablePropertyName;

/// <summary>
/// For use in entity / resource separation when the related property is also separated
/// </summary>
public string EntityPropertyName { get; }

/// <summary>
/// Sets the value of the property identified by this attribute
/// </summary>
Expand Down
6 changes: 3 additions & 3 deletions src/JsonApiDotNetCore/Models/RelationshipAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@ public bool TryGetHasMany(out HasManyAttribute result)
}

public abstract void SetValue(object entity, object newValue);

public object GetValue(object entity) => entity
?.GetType()
.GetProperty(InternalRelationshipName)
?.GetType()?
.GetProperty(InternalRelationshipName)?
.GetValue(entity);

public override string ToString()
Expand Down
48 changes: 48 additions & 0 deletions test/ResourceEntitySeparationExampleTests/Acceptance/AddTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,54 @@ public async Task Can_Create_Course()
Assert.Equal(course.Title, data.Title);
Assert.Equal(course.Description, data.Description);
}

[Fact]
public async Task Can_Create_Course_With_Department_Id()
{
// arrange
var route = $"/api/v1/courses/";
var course = _fixture.CourseFaker.Generate();

var department = _fixture.DepartmentFaker.Generate();
_fixture.Context.Departments.Add(department);
_fixture.Context.SaveChanges();

var content = new
{
data = new
{
type = "courses",
attributes = new Dictionary<string, object>
{
{ "number", course.Number },
{ "title", course.Title },
{ "description", course.Description }
},
relationships = new
{
department = new
{
data = new
{
type = "departments",
id = department.Id
}
}
}
}
};

// act
var (response, data) = await _fixture.PostAsync<CourseResource>(route, content);

// assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.NotNull(data);
Assert.Equal(course.Number, data.Number);
Assert.Equal(course.Title, data.Title);
Assert.Equal(course.Description, data.Description);
Assert.Equal(department.Id, data.DepartmentId);
}

[Fact]
public async Task Can_Create_Department()
Expand Down