Search code examples
c#.netrestasp.net-mvc-4odata

Cant select an entity by id in .net Odata Implementation


// GET api/Product/5
    public Product GET([FromODataUri]int id)
    {
        Product product = db.Products.Find(id);
        if (product == null)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }
        return product;
    

This above of getting entity with ID is never called with my url :

http://localhost:53208/odata/Product(1)

even with default settings in odata route this is not called.

First I was trying with this odata route settings:

 config.Routes.MapODataRoute("ODataRoute", "odata", GetEdmModel());

Remember my simple Get with queries is working fine, but this is the only thing which is working, and PUT method is working, others all are not working. This is view of controller. Please help.

public class ProductController : ODataController
{
    private OfferAssistantDbContext db = new OfferAssistantDbContext();

    // GET api/Product
    public IQueryable<Product> GET()
    {
       
        return db.Products.AsQueryable<Product>();
    }

    // GET api/Product/5
    public Product GET([FromODataUri]int id)
    {
        Product product = db.Products.Find(id);
        if (product == null)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }

        return product;
    }

Solution

  • Web API OData is particular with parameter names. The parameter name should be key instead of id i.e.

    public Product GET([FromODataUri]int key)
    {
    }