Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SingleResult<T> not serializable in Web API when querying by key

Trying to find single record using primary key CourseID against odata web.api using this:

var editedcourse = container.Courses.Where(c => c.CourseID == ID).SingleOrDefault();

This is error:

    <m:innererror>
    <m:message>The 'ObjectContent`1' type failed to serialize the response body for content type 'application/atom+xml; charset=utf-8'.</m:message>
    <m:type>System.InvalidOperationException</m:type>
    <m:stacktrace></m:stacktrace>
    <m:internalexception>
      <m:message>'SingleResult`1' cannot be serialized using the ODataMediaTypeFormatter.</m:message>
      <m:type>System.Runtime.Serialization.SerializationException</m:type>
like image 467
Steve Avatar asked Mar 31 '14 14:03

Steve


2 Answers

The web.api controller method by default was not queriable, thus client failed. Added annotation to fix: [Queryable(AllowedOrderByProperties = "Id")]

like image 136
Steve Avatar answered Sep 27 '22 19:09

Steve


Try adding the code below to your WebApiConfig.cs file.

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

I think the first two lines are optional if you don't use Json format.

Refer to http://social.msdn.microsoft.com/Forums/vstudio/en-US/a5adf07b-e622-4a12-872d-40c753417645/web-api-error-the-objectcontent1-type-failed-to-serialize-the-response-body-for-content?forum=wcf

like image 23
Feng Zhao Avatar answered Sep 27 '22 21:09

Feng Zhao