Odata serialization error for SingleResult.Create on an empty IQueryable

不问归期 提交于 2021-01-27 05:24:09

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/35573755/odata-serialization-error-for-singleresult-create-on-an-empty-iqueryable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!