2016-02-23 35 views
4

我使用的OData v4和試圖得到一個非常簡單的控制器工作:爲SingleResult.Create的OData序列化錯誤在一個空的IQueryable

控制器:

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()); 

當我打電話給服務定位/產品('abc')

如果abc是有效的代碼,我得到一個很好的JSON序列化的產品對象返回

ABC是一個無效的代碼中,我得到以下錯誤:

「SingleResult`1」不能使用ODataMediaTypeFormatter序列化。

在System.Web.OData.Formatter.ODataMediaTypeFormatter.GetSerializer(類型類型,對象的值,IEdmModel模型,ODataSerializerProvider serializerProvider)

我已經花了2天了尋找一個解決方案,但似乎沒有人得到這個問題?

回答

5

請參閱此變通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.

+0

絕對ledgend!應該問這個昨天哈哈!謝謝100萬 –

+0

我遇到了這個解決方法的問題。如果在其中一個SingleResults爲空的情況下使用$ batch請求,則它將爲整個$批處理返回404,而不僅僅是該部分。 – Tim

+0

有人可以請解釋如何使用解決方法的步驟?我對.NET新手會很有幫助 –