在空的IQueryable上进行SingleResult.Create的Odata序列化错误 [英] Odata serialization error for SingleResult.Create on an empty IQueryable
问题描述
我正在使用OData v4,并试图使一个非常简单的控制器正常工作:
I'm using OData v4 and trying to get a really simple controller working:
控制器:
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:
WebApiConfig:
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Product>("Product");
builder.EntityType<Product>().HasKey(p => p.Code);
config.MapODataServiceRoute("ODataRoute", null, builder.GetEdmModel());
当我致电servicelocation/Product('abc')
When I make a call to servicelocation/Product('abc')
如果abc是有效的代码,我会得到一个很好的JSON序列化的Product对象
If abc is a valid code, I get a nicely JSON serialized Product object back
如果abc是无效代码,则会出现以下错误:
If abc is an invalid code I get the following error:
'SingleResult`1'无法使用ODataMediaTypeFormatter进行序列化.
'SingleResult`1' cannot be serialized using the ODataMediaTypeFormatter.
在System.Web.OData.Formatter.ODataMediaTypeFormatter.GetSerializer(类型类型,对象值,IEdmModel模型,ODataSerializerProvider serializerProvider)
at System.Web.OData.Formatter.ODataMediaTypeFormatter.GetSerializer(Type type, Object value, IEdmModel model, ODataSerializerProvider serializerProvider)
我已经花了2天的时间寻找解决方案,但似乎没人能解决这个问题?
I've spent 2 days looking for a solution now but it seems nobody else gets this issue?
推荐答案
请在此处中查看此解决方法>
please see this workaround here
一种变通方法,它将识别SingleResult类型何时不包含任何结果,并将其替换为404,而不是引发SerializationException.
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.
这篇关于在空的IQueryable上进行SingleResult.Create的Odata序列化错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!