Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odata serialization error for SingleResult.Create on an empty IQueryable

I'm using OData v4 and trying to get a really simple controller working:

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 a valid code, I get a nicely JSON serialized Product object back

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

'SingleResult`1' cannot be serialized using the ODataMediaTypeFormatter.

at System.Web.OData.Formatter.ODataMediaTypeFormatter.GetSerializer(Type type, Object value, IEdmModel model, ODataSerializerProvider serializerProvider)

I've spent 2 days looking for a solution now but it seems nobody else gets this issue?

like image 563
Chris Surfleet Avatar asked Feb 23 '16 09:02

Chris Surfleet


1 Answers

please see this workaround here

A workaround that will recognise when a SingleResult type does not contain any results and replace it with a 404 instead of throwing a SerializationException.

like image 78
profesor79 Avatar answered Nov 16 '22 06:11

profesor79