2015-02-26 16 views
5

Tôi muốn quay trở lại đối tượng này bằng cách tìm nó bằng tên của nó:Không thể quay trở lại đối tượng

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

Phương pháp điều khiển là:

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

Và phương pháp WebApiConfig.Register() là:

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

Bằng cách gọi http://http://localhost:52542/Products(1) Tôi nhận sản phẩm có ID 1 như mong đợi:

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

Nhưng khi tôi gọi http://http://localhost:52542/Products/ProductService.GetByName(Name='yo-yo') tôi làm có thể gỡ lỗi vào chức năng điều khiển và kết quả đang được trả lại nhưng tôi nhận được một lỗi trong trình duyệt nói rằng An error has occurred.. Thông báo là The 'ObjectContent 1' type failed to serialize the response body for content type 'application/json; odata.metadata=minimal'. và ngoại lệ bên trong là 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..

Có gì sai ở đây?

Trả lời

5

Cấu hình chức năng của bạn có một số sự cố. Bạn nên gọi như sau để xác định sự trở lại:

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

Sau đó, nó có thể làm việc. Cảm ơn.

+0

Vì vậy, điều đó đã hiệu quả! Cảm ơn nhiều. Bây giờ tôi thấy sự khác biệt giữa mã của tôi và mã của bạn. –

+2

Tôi nhận thấy rằng việc học cách sử dụng 'ODataConventionModelBuilder' đúng cách không phải là một nhiệm vụ nhỏ. Không cảm thấy năng suất rất nhiều – bkwdesign

Các vấn đề liên quan