ElHaix
ElHaix

Reputation: 13006

Why don't ODataQueryOptions work for both sides of a 1..* relationship?

I have two tables that are joined by a link table and exposed through OData / Entity Framework:

Using ~/api/Users, the following [USER] API controller action returns results:

    public IEnumerable<USER> Get(ODataQueryOptions<USER> options)
    {
        var unitOfWork = new ATMS.Repository.UnitOfWork(_dbContext);

        var users = options.ApplyTo(unitOfWork.Repository<USER>().Queryable
                                              .Include(u => u.USERGROUPS)
                                              .OrderBy(order => order.USERNAME))
                                              .Cast<USER>().ToList();

        unitOfWork.Save();      // includes Dispose()

        return users;
    }

I am, however, unable to apply the ODataQueryOptions to the following [USERGROUP] API controller action:

    public IEnumerable<USERGROUP> Get(ODataQueryOptions<USER> options)
    {
        var unitOfWork = new ATMS.Repository.UnitOfWork(_dbContext);

        var userGroups = options.ApplyTo(unitOfWork.Repository<USERGROUP>().Queryable
                                .Include(u => u.USERS)
                                .OrderBy(order => order.GROUPNAME))
                                .Cast<USERGROUP>().ToList();

        unitOfWork.Save();      // includes Dispose()

        return userGroups.AsQueryable();
    }

When I do, I get the following error:

Cannot apply ODataQueryOptions of 'DAL.USER' to IQueryable of 'DAL.USERGROUP'.

Instead, I have to omit the options.ApplyTo(...):

        var userGroups = unitOfWork.Repository<USERGROUP>()
                                .Query()
                                .Include(u => u.USERS)
                                .Get()
                                .OrderBy(order => order.GROUPNAME);

Can someone please explain to me why this is?

Thanks.

Upvotes: 0

Views: 895

Answers (1)

RaghuRam Nadiminti
RaghuRam Nadiminti

Reputation: 6793

The error message says it all. You cannot apply a query meant to be applied on a collection of users on a collection of user groups. Change the parameter type to ODataQueryOptions<USERGROUP>.

Upvotes: 1

Related Questions