问题
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