smolesen
smolesen

Reputation: 1333

TableController and Odata Query

In a small Azure Mobile App, I have the following GET method in a tablecontroller:

    public IQueryable<User> GetAllUser()
    {
        return Query();
    }

using the following REST call, I can query users with the lastname='Tiger'

GET: ~/userinfo?$filter=lastName%20eq%20'Tiger'

Now I'd like to add an organisation fields to my user, so I've changed the get method to:

    public IQueryable<UserDto> GetAllUser()
    {
        return Query().Select(u => new UserDto{FirstName=u.FirstName, LastName=u.LastName, Organisation="Acme"});
    }

but now, when I try to query my users, using the same filter:

GET: ~/userinfo?$filter=lastName%20eq%20'Tiger'

I get an 'Bad Request' error....

How can I make this work...

Any help would be greatly appreciated....

Upvotes: 1

Views: 693

Answers (2)

Ben Hartmann
Ben Hartmann

Reputation: 31

Your post helped me solve my own issue!

From what I can tell, it doesn't work because when you're using DTO objects and MappedEntityDomainManager, this.Query() call crashes. In my case, both my Model and DTO object inherit from Azure.Mobile.Server.EntityData.

Basically... avoid this.Query() with MappedEntityDomainManager

Try this:

public IQueryable<UserDto> GetAllUser()
{
    return _context.User.Select(u => new UserDto{FirstName=u.FirstName, LastName=u.LastName, Organisation="Acme"});
}

where _context is your DBContext and .User is your User DBSet

Upvotes: 0

Dominique Alexandre
Dominique Alexandre

Reputation: 1053

Try:

public IQueryable<UserDto> GetAll()
{
    return Query().AsEnumerable().Select(u =>
            new UserDto
            {
                FirstName = u.FirstName,
                LastName = u.LastName,
                Organisation = "Acme"
            }).AsQueryable();
}

Your ODATA query will be used on the DTO and not the entity.

Your Controller should still use TableController<User>.

You could also use AutoMapper and simply do:

return Query().ProjectTo<UserDTO>();

This will do LINQ to Entities.

Upvotes: 1

Related Questions