public Document GetCollection() { ///////////////////////////////////////////////////// // Get all Articles from repository ///////////////////////////////////////////////////// var articles = BloggingRepository.GetArticles().SafeToList(); var articleToBlogIncludedResourceCollection = articles .Select(x => ToOneIncludedResource.Create(x, "blog", BloggingRepository.GetArticleToBlog(x.ArticleId))) .ToList(); var articleToAuthorIncludedResourceCollection = articles .Select(x => ToOneIncludedResource.Create(x, "author", BloggingRepository.GetArticleToAuthor(x.ArticleId))) .ToList(); var articleToCommentsIncludedResourcesCollection = articles .Select(x => ToManyIncludedResources.Create(x, "comments", BloggingRepository.GetArticleToComments(x.ArticleId))) .ToList(); // Get all distinct comments used in all the articles. var comments = articles .SelectMany(x => BloggingRepository.GetArticleToComments(x.ArticleId)) .GroupBy(x => x.CommentId) .Select(x => x.First()) .ToList(); var commentToAuthorIncludedResourceCollection = comments .Select(x => ToOneIncludedResource.Create(x, "author", BloggingRepository.GetCommentToAuthor(x.CommentId))) .ToList(); ///////////////////////////////////////////////////// // Build JSON API document ///////////////////////////////////////////////////// var currentRequestUri = this.Request.GetUri(); using (var documentContext = new BloggingDocumentContext(currentRequestUri)) { var document = documentContext .NewDocument(currentRequestUri) .SetJsonApiVersion(JsonApiVersion.Version10) .Links() .AddUpLink() .AddSelfLink() .LinksEnd() .ResourceCollection(articles) .Relationships() .AddRelationship("blog", new[] { Keywords.Related }) .AddRelationship("author", new[] { Keywords.Related }) .AddRelationship("comments", new[] { Keywords.Related }) .RelationshipsEnd() .Links() .AddSelfLink() .LinksEnd() .ResourceCollectionEnd() .Included() // article => blog (to-one) .Include(articleToBlogIncludedResourceCollection) .Links() .AddSelfLink() .LinksEnd() .IncludeEnd() // article => author (to-one) .Include(articleToAuthorIncludedResourceCollection) .Links() .AddSelfLink() .LinksEnd() .IncludeEnd() // article => comments (to-many) .Include(articleToCommentsIncludedResourcesCollection) .Relationships() .AddRelationship("author", new[] { Keywords.Related }) .RelationshipsEnd() .Links() .AddLink(Keywords.Self) .LinksEnd() .IncludeEnd() // comment => author (to-one) .Include(commentToAuthorIncludedResourceCollection) .Links() .AddSelfLink() .LinksEnd() .IncludeEnd() .IncludedEnd() .WriteDocument(); return(document); } }