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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With