Odata serialization error for SingleResult.Create on empty IQueryable

I am using OData v4 and trying to get a really simple controller:

Controller:

public class ProductController : ODataController
{
readonly MasterDataEntities db = new MasterDataEntities();

[EnableQuery(PageSize = MaxPageSize)]
public IQueryable<Product> Get()
{
    return db.Products;
}

[EnableQuery]
public SingleResult<Product> Get([FromODataUri] string key)
{
    return SingleResult.Create(db.Products.Where(p => p.Code == key));
}
}

WebApiConfig:

ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Product>("Product");
builder.EntityType<Product>().HasKey(p => p.Code);
config.MapODataServiceRoute("ODataRoute", null, builder.GetEdmModel());

When I make a call to servicelocation / Product ('abc')

If abc is valid code, I get a beautifully JSON serialized Product back object

If abc is invalid code, I get the following error:

'SingleResult`1' cannot be serialized using ODataMediaTypeFormatter.

in System.Web.OData.Formatter.ODataMediaTypeFormatter.GetSerializer (type of type, object value, IEdmModel model, ODataSerializerProvider serializerProvider)

I spent 2 days finding a solution, but nobody seems to be facing this problem anymore?

+4
1

.

, , SingleResult , 404 , SerializationException.

+5

Source: https://habr.com/ru/post/1630037/


All Articles