Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IQueryable serialization (web api)

Why isn't this working?:

        var surveys = db.Surveys.Where(s => s.Author.UserId == user.UserId);

        return from survey in surveys
               select new
               {
                   surveyId = survey.SurveyId,
                   title = survey.Title
               };

And this, with a minor change, is?:

        var surveys = db.Surveys.Where(s => s.Author == user);

        return from survey in surveys
               select new
               {
                   surveyId = survey.SurveyId,
                   title = survey.Title
               };

It throws a serialization error

The 'ObjectContent`1' type failed to serialize the response body for content type 
'application/xml; charset=utf-8'.  (...)




I'm fine with solving it that way, but I have the same error here (below), and can't solve it the same way:

var surveys = db.Surveys.Where(s => s.AnswerableBy(user));
like image 558
sports Avatar asked Sep 09 '12 04:09

sports


2 Answers

I ran into this issue recently, in my case the problem was that I had circular references created by the Entity Framework - Model First (Company -> Employee -> Company).

I resolved it by simply creating a view model object that had only the properties I needed.

like image 111
Ulises Avatar answered Oct 14 '22 05:10

Ulises


As per the section 'Handling Circular Object References' here on the Microsoft ASP.NET Web API website, add the following lines of code to the Register method of your WebAPIConfig.cs file (should be in the App_Start folder of your project).

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

There are separate instructions on that page for dealing with XML parsing.

like image 31
matias.berrueta Avatar answered Oct 14 '22 05:10

matias.berrueta