Skip to content

Allow filtering on properties of HasMany relationships #238

Closed
@jaredcnance

Description

@jaredcnance

Consider the following:

public class Foo : Identifiable
{
   [HasMany("bars")]
   public List<Bar> Bars { get; set; }
}

public class Bar : Identifiable
{
   [Attr("isActive")] public bool IsActive { get; set; }

   [HasOne("foo")]
   public Foo Foo { get; set; }
   public int FooId { get; set; }
}

If you try to filter

/foos?filter=bars.isActive=true

It will result in an exception

ArgumentException: 'IsActive' is not a member of type 'System.Collections.Generic.List`1[Bar]'
Parameter name: propertyOrFieldName
   at System.Linq.Expressions.Expression.PropertyOrField(Expression expression, String propertyOrFieldName)
   at JsonApiDotNetCore.Extensions.IQueryableExtensions.Filter[TSource](IQueryable`1 source, RelatedAttrFilterQuery filterQuery)
   at JsonApiDotNetCore.Services.EntityResourceService`2.ApplySortAndFilterQuery(IQueryable`1 entities)
   at JsonApiDotNetCore.Services.EntityResourceService`2.<GetAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at JsonApiDotNetCore.Controllers.BaseJsonApiController`2.<GetAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at JsonApiDotNetCore.Controllers.JsonApiController`2.<GetAsync>d__3.MoveNext()

We should consider an approach similar to EF Plus's IncludeFilter : http://entityframework-plus.net/query-include-filter

Workaround

The current workaround is to query the child resource directly and expose the parent id as an attribute on the resource:

GET /articles?filter[authorId]=1&filter[isActive]=true

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions