Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot return object

Tags:

c#

odata

odata-v4

I want to return this object by finding it by it's name:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Category { get; set; }
}

The controller method is:

[HttpGet]
[ODataRoute("Products/ProductService.GetByName(Name={name})")]
public IHttpActionResult GetByName([FromODataUri]string name)
{
    Product product = _db.Products.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
    if (product == null)
    {
        return NotFound();
    }

    return Ok(product);
}

And the WebApiConfig.Register() method is:

public static void Register(HttpConfiguration config)
{
    ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<Product>("Products");

    builder.Namespace = "ProductService";
    builder.EntityType<Product>().Collection.Function("GetByName").Returns<Product>().Parameter<string>("Name");

    config.MapODataServiceRoute(routeName: "ODataRoute", routePrefix: null, model: builder.GetEdmModel());
}

By calling http://http://localhost:52542/Products(1) I do get the product with the ID 1 as expected:

{
 "@odata.context":"http://localhost:52542/$metadata#Products/$entity","Id":1,"Name":"Yo-yo","Price":4.95,"Category":"Toy"
}

But when I'm calling http://http://localhost:52542/Products/ProductService.GetByName(Name='yo-yo') I do can debug into the controller function and the result is being returned but I get an error in the browser saying that An error has occurred.. The message is The 'ObjectContent 1' type failed to serialize the response body for content type 'application/json; odata.metadata=minimal'. and the inner exception is The related entity set or singleton cannot be found from the OData path. The related entity set or singleton is required to serialize the payload..

What is wrong here?

like image 967
Simon Linder Avatar asked Feb 26 '15 14:02

Simon Linder


1 Answers

Your function configuration has some problem. You should call as follows to define the return:

builder.EntityType<Product>().Collection.Function("GetByName").ReturnsFromEntitySet<Product>("Products").Parameter<string>("Name");

Then it can work. Thanks.

like image 106
Sam Xu Avatar answered Sep 28 '22 05:09

Sam Xu