5

我想通过它的名称找到它来返回这个对象:

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

控制器方法是:

[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);
}

WebApiConfig.Register()方法是:

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());
}

通过调用http://http://localhost:52542/Products(1),我确实得到了 ID 1 的产品,如预期的那样:

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

但是当我打电话时,http://http://localhost:52542/Products/ProductService.GetByName(Name='yo-yo')我可以调试到控制器函数并返回结果,但我在浏览器中收到错误消息An error has occurred.。消息是The 'ObjectContent 1' type failed to serialize the response body for content type 'application/json; odata.metadata=minimal'.,内部异常是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..

这里有什么问题?

4

1 回答 1

6

你的功能配置有问题。您应该按如下方式调用来定义返回:

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

然后它可以工作。谢谢。

于 2015-03-12T15:18:25.557 回答