OData ASP.Net Core on GET with Id?

asp.net-core c# entity-framework-core odata

Question

I'm trying to [EnableQuery] on a route (User) with id as example if I do a :

GET /users/1?$expand=Character

I'd like to get the User with Id 1 with its Character but currently it returns me null on the character :

{"character":null,"id":1,"username":"Iterer","password":"motdepasse","characterId":1}

But on the (global) route to get all users :

GET /users?$expand=Character

I get the user's character as you can see :

[{"character":{"id":1,"name":"Name"},"id":1,"username":"Iterer","password":"motdepasse","characterId":1}]

Here is my controller's actions :

    // GET: api/Users
    [HttpGet]
    [EnableQuery]
    public ActionResult<IQueryable<UserEntity>> GetUsers()
    {
        return Ok(_context.Users);
    }

    // GET: api/Users/5
    [HttpGet("{id}")]
    [EnableQuery]
    public ActionResult<IQueryable<UserEntity>> GetUserEntity(long id)
    {
        var userEntity = _context.Users.Where(u => u.Id == id).FirstOrDefault();

        if (userEntity == null)
        {
            return NotFound();
        }

        return Ok(userEntity);
    }

Both use IQueryable interface but I still don't understand why it doesn't works, here is the full controller :

https://github.com/myerffoeg/gaium-api/blob/master/Gaium/Controllers/UsersController.cs

and my startup file :

https://github.com/myerffoeg/gaium-api/blob/master/Gaium/Startup.cs

Moreover, if you have some best practices to share it would be appreciated thanks!

1
3
5/5/2019 10:52:20 AM

Accepted Answer

Both use IQueryable interface but I still don't understand why it doesn't works

Well, the difference is that while to "non working" method claims to return IQueryable<UserEntity>:

public ActionResult<IQueryable<UserEntity>> GetUserEntity(long id)

the implementation returns single materialized UserEntity instance.

In order to match the claim, the implementation should be like this instead (basically the first method with Where clause applied):

return Ok(_context.Users.Where(u => u.Id == id));
3
5/5/2019 12:29:11 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow