2015-02-26 10 views
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) पर कॉल करके मुझे आईडी 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. है।

यहां क्या गलत है?

उत्तर

5

आपकी फ़ंक्शन कॉन्फ़िगरेशन में कुछ समस्या है। आप के रूप में वापसी को परिभाषित करने के इस प्रकार बुलाना चाहिए:

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

तो यह काम कर सकते हैं। धन्यवाद।

+0

तो यह काम किया! बहुत धन्यवाद। अब मैं अपने कोड और आपके कोड के बीच का अंतर देखता हूं। –

+2

मुझे लगता है कि 'ODataConventionModelBuilder' का उपयोग कैसे करें सीखना कोई छोटा काम नहीं है। उत्पादकता बहुत ज्यादा महसूस नहीं कर रहा है – bkwdesign

संबंधित मुद्दे