Chcę zwrócić ten przedmiot poprzez znalezienie go przez jego nazwę:nie może wrócić obiekt
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
Metoda kontroler jest:
[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);
}
A metoda WebApiConfig.Register()
jest:
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());
}
Dzwoniąc pod numer http://http://localhost:52542/Products(1)
, otrzymuję produkt o identyfikatorze 1 zgodnie z oczekiwaniami:
{
"@odata.context":"http://localhost:52542/$metadata#Products/$entity","Id":1,"Name":"Yo-yo","Price":4.95,"Category":"Toy"
}
Ale kiedy dzwonię http://http://localhost:52542/Products/ProductService.GetByName(Name='yo-yo')
robię można debugować do funkcji kontrolera, a wynik jest zwracany, ale pojawia się błąd w przeglądarce mówiąc, że An error has occurred.
. Komunikat to The 'ObjectContent 1' type failed to serialize the response body for content type 'application/json; odata.metadata=minimal'.
, a wewnętrzny wyjątek to 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.
.
Co jest nie tak?
Tak więc zadziałało! Wielkie dzięki. Teraz widzę różnicę między moim kodem a kodem. –
Zauważyłem, że uczenie się, jak poprawnie używać 'ODataConventionModelBuilder' nie jest małym zadaniem. Nie czuję tak bardzo wydajności – bkwdesign