Skip to content

Fixed HasManyThrough relationships returning empty data array without 'include' #456

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
Changes from all 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
17 changes: 12 additions & 5 deletions src/JsonApiDotNetCore/Internal/ResourceGraph.cs
Original file line number Diff line number Diff line change
@@ -144,11 +144,18 @@ private IEnumerable<IIdentifiable> GetHasManyThrough(IIdentifiable parent, HasMa
var throughProperty = GetRelationship(parent, hasManyThrough.InternalThroughName);
if (throughProperty is IEnumerable hasManyNavigationEntity)
{
foreach (var includedEntity in hasManyNavigationEntity)
{
var targetValue = hasManyThrough.RightProperty.GetValue(includedEntity) as IIdentifiable;
yield return targetValue;
}
// wrap "yield return" in a sub-function so we can correctly return null if the property is null.
return GetHasManyThroughIter(hasManyThrough, hasManyNavigationEntity);
}
return null;
}

private IEnumerable<IIdentifiable> GetHasManyThroughIter(HasManyThroughAttribute hasManyThrough, IEnumerable hasManyNavigationEntity)
{
foreach (var includedEntity in hasManyNavigationEntity)
{
var targetValue = hasManyThrough.RightProperty.GetValue(includedEntity) as IIdentifiable;
yield return targetValue;
}
}

30 changes: 29 additions & 1 deletion test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs
Original file line number Diff line number Diff line change
@@ -110,6 +110,34 @@ public async Task Can_Fetch_Many_To_Many_Through_GetById()
Assert.Equal(tag.Name, tagResponse.Name);
}

[Fact]
public async Task Can_Fetch_Many_To_Many_Without_Include()
{
// arrange
var context = _fixture.GetService<AppDbContext>();
var article = _articleFaker.Generate();
var tag = _tagFaker.Generate();
var articleTag = new ArticleTag
{
Article = article,
Tag = tag
};
context.ArticleTags.Add(articleTag);
await context.SaveChangesAsync();

var route = $"/api/v1/articles/{article.Id}";

// act
var response = await _fixture.Client.GetAsync(route);

// assert
var body = await response.Content.ReadAsStringAsync();
Assert.True(HttpStatusCode.OK == response.StatusCode, $"{route} returned {response.StatusCode} status code with payload: {body}");

var document = JsonConvert.DeserializeObject<Document>(body);
Assert.Null(document.Data.Relationships["tags"].ManyData);
}

[Fact]
public async Task Can_Create_Many_To_Many()
{
@@ -269,4 +297,4 @@ public async Task Can_Update_Many_To_Many_Through_Relationship_Link()
Assert.Equal(tag.Id, persistedArticleTag.TagId);
}
}
}
}