Question

I am unable to use $expand on a single entity, but it works fine on a collection. I have the following asynchronous OData Web API controller:

public class AuthorController : AsyncEntitySetController<Author, int>
{
    private readonly IAuthorRepository _AuthorRepo = new AuthorRepository();

    // GET odata/<controller>
    [Queryable]
    public override async Task<IEnumerable<Author>> Get()
    {
        var authors = await _AuthorRepo.GetAll();
        return authors.AsQueryable();
    }

    // GET odata/<controller>/5
    [Queryable]
    public async Task<Author> Get([FromODataUri]int key)
    {
        var author = await _AuthorRepo.GetById(key);
        return author;
    }
}

Requesting the collection via https://api.acme.org/odata/Authors works, and so does expanding the authors' books via https://api.acme.org/odata/Authors?$expand=Books.

However, attempting to expand a single entity using the Get method above that accepts a key parameter via https://api.acme.org/odata/Authors(1)?$expand=Books yields the following error:

Multiple actions were found that match the request: Get on type AcmeApi.Controllers.AuthorsController Get on type AcmeApi.Controllers.AuthorssController

Upon reading the answer to this question, I tried returning a SingleResult by updating my second Get method to:

[Queryable]
public SingleResult<Account> Get([FromODataUri]int key)
{
    return SingleResult.Create<Account>(m_AccountRepo.GetById(key));
}

But this results in the following compilation error:

Argument 1: cannot convert from 'System.Threading.Tasks.Task' to 'System.Linq.IQueryable'

The asynchronous GetById repository method is:

public async Task<Author> GetById(int id)
{
    return await Task.Run(() => _Authors.Where(a => a.Id == id).SingleOrDefault());
}

If returning a SingleResult is the way to get $expand to work for a single entity, what is the correct way to do so from an asynchronous controller?

Was it helpful?

Solution

Rename Get([FromOdataUri]int key) to GetAuthor([]int) may resolve this issue.
Please refer this post: http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-routing-conventions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top